Reputation: 21247
I'm trying to write a small class to handle permission checking. Only problem is that onRequestPermissionsResult() never gets called:
class PermissionHelper(val activity: Activity) : ActivityCompat.OnRequestPermissionsResultCallback{
interface OnPermissionRequested {
fun onPermissionResponse(isPermissionGranted: Boolean)
}
private var listener: OnPermissionRequested? = null
fun isPermissionGranted(permission: String) : Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return activity.applicationContext.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
}
return true
}
fun requestPermission(permissions: Array<String>,
requestCode: Int,
listener: OnPermissionRequested) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
this.listener = listener
activity.requestPermissions(permissions, requestCode)
}
}
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray) {
val isPermissionGranted = grantResults.isNotEmpty() &&
grantResults[0] == PackageManager.PERMISSION_GRANTED
listener?.onPermissionResponse(isPermissionGranted)
}
companion object {
const val PERMISSIONS_REQUEST_READ_CALENDAR = 200
const val PERMISSIONS_REQUEST_WRITE_CALENDAR = 201
const val PERMISSIONS_REQUEST_CALENDAR = 101
const val PERMISSIONS_REQUEST_LOCATION = 102
const val READ_CALENDAR = Manifest.permission.READ_CALENDAR
const val WRITE_CALENDAR = Manifest.permission.WRITE_CALENDAR
const val ACCESS_FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION
}
}
The system dialog to request the permission pops up, but the response is never handled. (i.e. the break point inside onRequestPermissionsResult() is never hit). Nothing is null, and all values are correct.
Thanks for any help.
Upvotes: 0
Views: 807
Reputation: 7009
In 2023 you have to use ActivityResultLauncher
to handle granted (or declined) permissions.
https://developer.android.com/training/permissions/requesting
It is not quite convenient and ask Android team for a new feature proposed here: https://issuetracker.google.com/issues/293387810
Upvotes: 0
Reputation: 99
My suggestion is use this library for handle permissions: https://github.com/Karumi/Dexter
If you don't want to use Dexter library, I suggest use ActivityCompat.requestPermissions()
instead of activity.requestPermissions()
You can find more info in this answer: https://stackoverflow.com/a/56761238/5661680
Upvotes: 0
Reputation: 29380
onRequestPermissionsResult
will be called on your Activity
. There is nothing in this code that is going to call the onRequestPermissionsResult
of your PermissionHelper
.
You need this in your activity
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray) {
helper.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
Upvotes: 1