Location Permission Handler
Easy way to check location permissions for Android 9/10/11 devices. Project can be integrated with your existing ones thanks to kotlin extension functions.
Usage
In your fragment, to check any permissions (not only location permissions) you can call directly with :
fun Fragment.handlePermission(
permission: AppPermission,
onGranted: (AppPermission) -> Unit,
onDenied: (AppPermission) -> Unit,
onRationaleNeeded: ((AppPermission) -> Unit)? = null
)
AppPermission class takes two parameters :
sealed class AppPermission(
val permissionName: String,
val requestCode: Int
)
Example usage in fragments :
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
handlePermission(
AppPermission.ACCESS_COARSE_LOCATION,
onGranted = { checkDeviceLocationSetting() },
onDenied = { requestPermission(AppPermission.ACCESS_COARSE_LOCATION) },
onRationaleNeeded = { showToast("onRationaleNeeded")}
)
}
Afterwards override onRequestPermissionsResult() in fragment :
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
handlePermissionsResult(requestCode, permissions, grantResults,
onPermissionGranted = { showToast("onPermissionGranted") },
onPermissionDenied = { showToast("onPermissionDenied") },
onPermissionDeniedPermanently = { showToast("onPermissionDeniedPermanently") }
)
}
Acknowledgement
- @Ace's answer on stackoverflow.
- @amsterdatech's gist file.
To-Do
- Deprecated onRequestPermissionsResult will be replaced with registerForActivityResult()