Requesting permission is just a simple method call to PermissionManager
from your Activity/Fragment. It takes 3 parameters.
- An instance of AppCompactActivity or Fragment depending from where you are requesting permission.
- Request id.
- varargs of permission you want to request.
This is how you request permissions from your Activity/Fragment.
PermissionManager.requestPermissions(
this,
REQUEST_ID,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.READ_CONTACTS
)
With just one simple step(implementing an interface) you are ready to observe the result of request.
Your Activity/Fragment must implement setupObserver
method of PermissionObserver
interface which expose LiveData<PermissionResult
>. Here is the definition of PermissionObserver
/**
* Interface definition for a callback to get [LiveData] of [PermissionResult]
*
* Implement this interface to get [LiveData] for observing permission request result.
*/
interface PermissionObserver {
fun setupObserver(permissionResultLiveData: LiveData<PermissionResult>)
}
The library will only call setupObserver
method when you are requesting permission for the first time. All the successive call to requestPermissions
method will use the same observer.
Just as you would observe other LiveData you can observe LiveData<PermissionResult
> as follow
override fun setupObserver(permissionResultLiveData: LiveData<PermissionResult>) {
permissionResultLiveData.observe(this, Observer<PermissionResult> {
when (it) {
is PermissionResult.PermissionGranted -> {
if (it.requestId == REQUEST_ID) {
//Add your logic here after user grants permission(s)
}
}
is PermissionResult.PermissionDenied -> {
if (it.requestId == REQUEST_ID) {
//Add your logic to handle permission denial
}
}
is PermissionResult.PermissionDeniedPermanently -> {
if (it.requestId == REQUEST_ID) {
//Add your logic here if user denied permission(s) permanently.
//Ideally you should ask user to manually go to settings and enable permission(s)
}
}
is PermissionResult.ShowRational -> {
if (it.requestId == REQUEST_ID) {
//If user denied permission frequently then she/he is not clear about why you are asking this permission.
//This is your chance to explain them why you need permission.
}
}
}
})
}
It is mandatory to implement
PermissionObserver
from where you are requesting permission(either Activity or Fragment). If you don't then library will throwIllegalArgumentException
stating that you have to implementPermissionObserver
Library will take care of Activity/Fragment recreation so even if user rotates screen or due to some other reason if your Activity/Fragment gets recreated it will call setupObserver
method to register new observer of LiveData.