A useful function to determine if an arbitrary permission has been blocked from requesting (in Kotlin):
private fun isPermissionBlockedFromAsking(activity: Activity, permission: String): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED
&& !activity.shouldShowRequestPermissionRationale(permission)
&& PreferenceManager.getDefaultSharedPreferences(activity).getBoolean(permission, false)
}
return false
}
Use of this requires setting a shared preference boolean with the name of your desired permission (e.g. android.Manifest.permission.READ_PHONE_STATE
) to true
when you first request a permission.
Explanation:
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
as some of the code may only be run on API level 23+.
ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED
to check we don't already have the permission.
!activity.shouldShowRequestPermissionRationale(permission)
to check whether the user has denied the app asking again. Due to quirks of this function, the following line is also required.
PreferenceManager.getDefaultSharedPreferences(activity).getBoolean(permission, false)
this is used (along with setting the value to true on first permission request) to distinguish between the "Never asked" and "Never ask again" states, as the previous line doesn't return this information.