Permissions with the easiest way

Emre Hamurcu
2 min readApr 14, 2022

--

Have you ever needed to use a library for permissions only ? Most popular answer is YES, but you will not need anymore!

There is also a Turkish version of this story in my website you can check it!

if your app is installed on a device that runs Android 6.0 (API level 23) or higher, you must request the dangerous permissions at runtime. There are a lots of libraries can do it but forget all of them we will handle it today :)

First of all let’s understand how permissions works!

https://developer.android.com/training/permissions/requesting

As you can see, firstly we should declare the permissions in manifest file, then make a request .

We can use the easy way for make a request a permission quickly by using registerForActivityResult,but I think there is missing part here. If the user denied permission permanently this method does not cover it. It gives us only the granted or denied states. Don’t worry we will add an extra state.

How can we handle if user denied a permission permanently ?

Making a request was the easy part but if the user clicks permanently denied it, request popup will never shows again. We should navigate the user to settings page if its required. First of all we should know if permission is denied permanently .

We have a wonderfull function which is shouldShowRequestPermissionRationale as you can see above. It takes two parameters which are activity and permission. It returns a boolean value. Lets mix all of them step by step !

Step 1

Create a sealed class that includes Granted,Denied and Permanently denied states

Step 2

We want to handle multiple and single permissions so If you check registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) fun you will see it returns ActivityResultLauncher<Array<String>>, so I decided to use inline class to wrap it.

Step 3

Create extensions with higher order function to handle the result and be more clear.

Step 4

Getting permisson state with helper function below.

Final Step

Finally we can write last extensions for launch single and multiple permissions.

How to use it ?

So as you can see we do not need any permission library anymore.If you have any advice or opinion please share it! Information multiplies as it is shared . I also pushed all the code on my github. Please subscribe and do not forget your claps, have a good and clean coding days.

--

--

Emre Hamurcu
Emre Hamurcu

Written by Emre Hamurcu

Senior Android Developer & Youtuber

Responses (1)