Permissions in Android Application

How to add/request for permissions in an Android Application - Using Android Studio and Java

Permissions in Android Application

Every Android app runs in a limited-access sandbox. If our app needs to use resources outside its sandbox, we can declare permission and set up a permission request that provides this access.

Starting from Android 6.0 (API 23), if any dangerous permissions are declared, they need to be requested at the run time. These are called Run-Time Permissions, i.e., which can be requested at run time. If there are no dangerous permissions declared, or it is Android 5.1 (API 22) or lower, the permissions are automatically granted. These are called Install-Time Permissions, i.e., they are requested at the time of installation from the Google Play Store.

Now, let's see how to request run-time permissions from the user.

First, declare the permissions in the AndroidManifest.xml as shown below. carbon.png

Let's say we want to access the camera. So, the above code becomes carbon (1).png

Also, declare all the permissions in an array of String data-type. Now, let's say we want to request permissions (declared in AndroidManifest.xml) from the user by pressing a Button button (or at the start of our application). We first need to check if the permissions have already been granted and, if not, request the permissions using the following code snippet.

carbon (3).png

The above methods can be called as shown below.

carbon (4).png

Finally, onRequestPermissionsResult() is called when the user grants or declines the permission. Using the onRequestPermissionsResult() method is optional. One of the parameters of the onRequestPermissionsResult() method is requestCode, which is used to check which permission called this function. This requestCode is provided when the user is prompted for permission. The following code snippet can be used to take some action when the user grants or declines the permission.

carbon (6).png

In this way, we can request run-time permissions from the user in an android application.