Every Android application runs inside limited access sandbox. Now if the application needs to access external resources like internal storage then we have specific permission to access that resource. Android comes with different resources. Some of them are Camera, GPS, Storage, etc. From the Android API level, 23(Marshmallow) concept of runtime permissions was introduced. In this post, we will see Android Runtime Permissions Example in detail.

SOURCE CODE

DEMO

OVERVIEW

Now let’s suppose you want access camera of device, then you will define camera permission inside manifest as shown below.

<uses-permission android:name=”android.permission.CAMERA” />

But this is not enough for devices having API level greater than or equal to 23(Marshmallow). Your app is going to crash on those devices. To use camera in those device you need to define camera permission inside manifest and ask for permission in runtime. You can ask for camera permission in runtime as shown below

// Check Camera Permission already granted or not
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
    Toast.makeText(MainActivity.this, "Camera permission is already granted", Toast.LENGTH_SHORT).show();
} else {
    // Request Camera Permission
    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST_CODE);
        }

Now in above code first we will check that camera permission already granted, if it is already then we can directly launch camera otherwise we will request for camera permission.

Now question comes in how we are going to know that user allowed or denied the permission. When we will ask for permission android system will popup a dialogue as shown below

android runtime permission dialogue
android runtime permission dialogue

User will either allow permission or deny it. We will get this result inside android activity lifecycle  method onRequestPermissionsResult() as shown below.

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case CAMERA_PERMISSION_REQUEST_CODE:
                // Check Camera permission is granted or not
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, "Camera  permission granted", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Camera  permission denied", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

In above code we checking if request code matches with request code sent by us while requesting permission. If request code matches then we are checking user allowed or denied permission. If user grants permission then we can initialize camera otherwise show some message that will make user to allow permission.

Android Runtime Permissions Example

Now let’s build android application which will ask user runtime permissions. In this example i will be demonstrating how to ask  for camera and location permission also we will learn to ask multiple permissions at single time.

STEP 1: Create or open existing android studio application.

STEP 2: Let’s create activity which will contain three buttons for requesting location, Camera and multiple permission. Create new layout inside res -> layout -> activity_main.xml add below lines of code in it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_margin="16dp"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/buttonRequestLocationPermission"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Request Location Permission" />

    <Button
        android:id="@+id/buttonRequestCameraPermission"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Request Camera Permission" />

    <Button
        android:id="@+id/buttonRequestMultiplePermission"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Request Multiple Permissions" />

</LinearLayout>

Create new class inside Package name -> MainActivity.java add below lines in it.

package com.loopwiki.androidruntimepermissions;

import android.Manifest;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    // Location Permission Request Code
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;

    // Camera Permission Request Code
    private static final int CAMERA_PERMISSION_REQUEST_CODE = 2;

    // Multiple Permission Request Code
    private static final int MULTIPLE_PERMISSION_REQUEST_CODE = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button buttonRequestLocationPermission = findViewById(R.id.buttonRequestLocationPermission);
        buttonRequestLocationPermission.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //Check Location Permission already granted or not
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, "Location permission is already granted", Toast.LENGTH_SHORT).show();
                } else {
                    // Request Location Permission
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
                }
            }
        });
        Button buttonRequestCameraPermission = findViewById(R.id.buttonRequestCameraPermission);
        buttonRequestCameraPermission.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Check Camera Permission already granted or not
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, "Camera permission is already granted", Toast.LENGTH_SHORT).show();
                } else {
                    // Request Camera Permission
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST_CODE);
                }
            }
        });
        Button buttonRequestMultiplePermission = findViewById(R.id.buttonRequestMultiplePermission);
        buttonRequestMultiplePermission.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Check Camera &amp; Location Permission already granted or not
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                        &amp;&amp; ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, "Location and Camera permissions are already granted", Toast.LENGTH_SHORT).show();
                } else {
                    // Request Camera &amp; Location Permission
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CAMERA}, MULTIPLE_PERMISSION_REQUEST_CODE);
                }
            }
        });
    }


    // When we request permission user will either allow or deny the permission which can be checked inside onRequestPermissionsResult method
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case LOCATION_PERMISSION_REQUEST_CODE:

                // Check Location permission is granted or not
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, "Location  permission granted", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Location  permission denied", Toast.LENGTH_SHORT).show();
                }
                break;
            case CAMERA_PERMISSION_REQUEST_CODE:

                // Check Camera permission is granted or not
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, "Camera  permission granted", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Camera  permission denied", Toast.LENGTH_SHORT).show();
                }
                break;
            case MULTIPLE_PERMISSION_REQUEST_CODE:

                // Check Location permission is granted or not
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, "Location  permission granted", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Location  permission denied", Toast.LENGTH_SHORT).show();
                }

                // Check Camera permission is granted or not
                if (grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, "Camera  permission granted", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Camera  permission denied", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}

Now as you can see in above code on the click of button i am requesting permission.

STEP 3: Now don’t forgot add all the permissions inside manifest too as given below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.loopwiki.androidruntimepermissions">

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="Android Runtime Permissions"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

STEP 4: Create new file inside res -> values -> styles.xml add below line of code in it.

<resources>

    <! – Base application theme. – >
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <! – Customize your theme here. – >
        <item name="colorPrimary">#008577</item>
        <item name="colorPrimaryDark">#00574B</item>
        <item name="colorAccent">#D81B60</item>
    </style>

</resources>

STEP 5: Run the application and click on any of the button request respective permission.

android runtime permission example
android runtime permission example

If you still have any queries, please post them in the comments section below, I will be happy to help you.

Author

Hello there, My name is Amardeep founder of loopwiki.com. I have experience in many technologies like Android, Java, Php, etc. In this variety of technologies, I love Android App Development. If you have any idea and you want me to develop for you then let's have chat Conatct

Write A Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.