Validating permissions on Android with Kotlin
I’m continuing my educational coding exercise, developing a new photo sharing app. Recently, I completed my user authentication and registration process and I’m now quite happy with it, so I moved on to taking photographs. I’ve got an activity with a toolbar and a floating action button:
In the MainActivity
, I’ve set up an onClickListener
as follows:
The question before me is this: How do I ask for permissions on Android?
The hard way
Naturally, Android has its own system of doing things. It boils down to this:
- Declare the permissions you want in your
AndroidManifest.xml
file. - Use
ContextCompat.checkSelfPermission()
to see if you have the permission. - If you don’t have the permission, show the rationale, and request permissions.
- Define a callback to receive the result of the request permissions.
It’s actually a lot of boiler plate code, which I won’t show here because the android.developer.com has already done it.
The easy way
This left me searching for an alternate way, and I found it in a small library called Dexter - contributed to open source (Apache 2.0 licensed) by Karumi. Basically, it simplifies the way you ask for permissions.
In my case, I need to ask for multiple permissions, so let’s go through the process. First, we declare the permissions in the AndroidManifest.xml
file:
Next, add the library to the app-level build.gradle
:
Don’t forget to sync.
Finally, call Dexter in your app to check for licenses:
We declare the list of permissions we want in the .withPermissions()
and then add a callback that is called when it wants something. In this case, once I’ve got all the permissions approved, I call launchCamera()
. If the permissions failed, then it drops through and returns - nothing actually happens.
There is another version of this that provides an onFailure
callback for checking an individual permission. This allows you, for example, to disable the camera button when you get a declined to prevent the user from clicking the button in the future.
You can see the code for this in my GitHub repository.
Leave a comment