Requesting Runtime Permission – Part 1

In previous post we have discussed about theory part of Android’s Runtime Permission. Today we will discuss about Requesting Runtime Permission through coding.

As you all know it is Marshmallow functionality so start your new project by setting compileSdkVersion and targetSdkVersion to 23 and mention permission in manifest.xml file.

Now we will check whether READ_EXTERNAL_STORAGE permission is Granted or not with help of checkSelfPermission().

It will give you int value. If permission is given by user, it will return 0 else will return 1. If permission is not given by user we will request for permission at runtime with using below code.

requestPermissions(), This method functions asynchronously: it returns right away, and after the user responds to the dialog box, the system calls the app’s callback method with the results, passing the same request code that the app passed to requestPermissions().

Requesting Runtime Permission - Part 1

 

No matter Allow or Deny is chosen, Activity’s onRequestPermissionsResult will always be called to inform a result which we can check from the 3rd parameter, int[] grantResults, like this:

This is how Requesting Runtime Permission works. It’s quite complicated but you have to use it in your application for other permissions like above.

What if user select “Never ask again”

If user denied a permission. In the second launch, user will get a “Never ask again” option to prevent application from asking this permission in the future.

Requesting Runtime Permission - Part 1

If this option is checked before denying. Next time we call requestPermissions, this dialog will not be appeared for this kind of permission anymore. Instead, it just does nothing.

shouldShowRequestPermissionRationale() will be used to check whether user have selected “Never ask again“. It will return value as True or False, If user have selected Never ask before it will return false, else will return true.

There you can give clerification about “why you need this permission and move user to permission setting screen.

permission3

Here you are done with Requesting Runtime Permission, in next part of this tutorial we will learn How to ask for multiple permissions at a time.

Follow me

Ravi Rupareliya

He is author of Android Gig. He loves to explore new technologies and have worked on Android, React Native, Action on Google and Flutter.
Ravi Rupareliya
Follow me
Android’s Runtime Permission
Requesting Runtime Permission – Part 2