original (not mine) post here
For special permissions, such as android.Manifest.permission.PACKAGE_USAGE_STATS
used AppOpsManager
:
Kotlin
private fun hasPermission(permission:String, permissionAppOpsManager:String): Boolean {
var granted = false
if (VERSION.SDK_INT >= VERSION_CODES.M) {
// requires kitkat
val appOps = applicationContext!!.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
// requires lollipop
val mode = appOps.checkOpNoThrow(permissionAppOpsManager,
android.os.Process.myUid(), applicationContext!!.packageName)
if (mode == AppOpsManager.MODE_DEFAULT) {
granted = applicationContext!!.checkCallingOrSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
} else {
granted = mode == AppOpsManager.MODE_ALLOWED
}
}
return granted
}
and anywhere in code:
val permissionAppOpsManager = AppOpsManager.OPSTR_GET_USAGE_STATS
val permission = android.Manifest.permission.PACKAGE_USAGE_STATS
val permissionActivity = Settings.ACTION_USAGE_ACCESS_SETTINGS
if (hasPermission(permission, permissionAppOpsManager)) {
Timber.i("has permission: $permission")
// do here what needs permission
} else {
Timber.e("has no permission: $permission")
// start activity to get permission
startActivity(Intent(permissionActivity))
}
Other permissions you can get with TedPermission library