Skip to content

Instantly share code, notes, and snippets.

@roschlau

roschlau/BaseActivity.kt

Last active Mar 19, 2018
Embed
What would you like to do?
Utility class for handling permissions on Android
class BaseActivity : Activity {
val permissionHandler: PermissionRequestHandler
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
val handled = permissionHandler.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(!handled) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
}
class PermissionRequestHandler(val activity: Activity) {
val permissionCallbacks = mutableMapOf<Int, PermissionCallbacks>()
val requestCodes = generateSequence(0) { it + 1 }.iterator()
data class PermissionCallbacks(val onGranted: () -> Unit,
val onDenied: (() -> Unit)? = null)
fun needPermission(
permission: String,
beforeRequest: (() -> Unit)? = null,
onDenied: (() -> Unit)? = null,
onGranted: () -> Unit
) {
if(hasPermission(permission)) {
onGranted()
} else {
beforeRequest?.invoke()
val requestCode = requestCodes.next()
permissionCallbacks[requestCode] = PermissionCallbacks(onGranted, onDenied)
ActivityCompat.requestPermissions(activity, arrayOf(permission), requestCode)
}
}
fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>,
grantResults: IntArray): Boolean {
val (onGranted, onDenied) = permissionCallbacks[requestCode]
?: return false
if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
onGranted()
} else {
onDenied?.invoke()
}
return true
}
fun hasPermission(perm: String) = activity.hasPermission(perm)
}
fun Context.hasPermission(perm: String): Boolean =
ContextCompat.checkSelfPermission(this, perm) == PackageManager.PERMISSION_GRANTED
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment