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!
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 !
Create a sealed class that includes Granted,Denied and Permanently denied states
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.
Create extensions with higher order function to handle the result and be more clear.
Getting permisson state with helper function below.
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. You can get the final gist from here and use it in your projects. 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.