The Wayback Machine - https://web.archive.org/web/20240601234128/https://www.geeksforgeeks.org/easy-runtime-permissions-in-android-with-dexter/
Open In App

Easy Runtime Permissions in Android with Dexter

Last Updated : 15 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The Runtime Permission in Android which introduced in Marshmallow and due to these runtime permissions users can grant permission to the app in runtime, also while writing the code for runtime permissions. Sometimes handling the task of requesting permissions becomes so difficult and the developer has to write a huge amount of code. So we will see the Implementation of Runtime Permissions in Android using Dexter. 

What is Dexter in Android?

Dexter is the library that will help us to make this task easy for handling Runtime Permissions in Android. Now we will see the implementation of this in our Android Application. 

What are we going to Build in this Article? 

We will be building a simple application in which we will be showing a button to the user. After clicking on that button we will display runtime permissions to the user. So if the users deny the permission then we are showing the option to open the settings screen and grant the permissions. Below is the short video in which we will see what we will build in this article.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Project just refer to this article on How to Create New Project in Android Studio. The code has been given in both Java and Kotlin Programming Language for Android.

Step 2: Add Dependency of Dexter Runtime Permissions in build.gradle File

Navigate to gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section.

implementation 'com.karumi:dexter:6.2.2'

After adding this dependency now sync your project. Let’s move toward the XML part. 

Step 3: Working with the activity_main.xml File

Go to the activity_main.xml File and refer to the following code. Below is the code for the activity_main.xml File.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
  
    <!-- Button to request permissions -->
    <Button
        android:id="@+id/idBtnRequestPermission"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Request Permission"
        android:textAllCaps="false" />
</RelativeLayout>


Step 4: Working with the MainActivity File

Go to the MainActivity File and refer to the following code. Comments are added inside the code to understand the code in more detail.

Java




import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
import java.util.List;
  
public class MainActivity extends AppCompatActivity {
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // initializing our button and adding on click listener to it.
        Button requestPermissionsBtn = findViewById(R.id.idBtnRequestPermission);
        requestPermissionsBtn.setOnClickListener(v -> {
            // inside on click listener calling method to request permission
            requestPermissions();
        });
    }
  
    private void requestPermissions() {
        // below line is use to request permission in the current activity.
        // this method is use to handle error in runtime permissions
        Dexter.withActivity(this)
                // below line is use to request the number of permissions which are required in our app.
                .withPermissions(Manifest.permission.CAMERA,
                        // below is the list of permissions
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.READ_CONTACTS)
                // after adding permissions we are calling an with listener method.
                .withListener(new MultiplePermissionsListener() {
                    @Override
                    public void onPermissionsChecked(MultiplePermissionsReport multiplePermissionsReport) {
                        // this method is called when all permissions are granted
                        if (multiplePermissionsReport.areAllPermissionsGranted()) {
                            // do you work now
                            Toast.makeText(MainActivity.this, "All the permissions are granted..", Toast.LENGTH_SHORT).show();
                        }
                        // check for permanent denial of any permission
                        if (multiplePermissionsReport.isAnyPermissionPermanentlyDenied()) {
                            // permission is denied permanently, we will show user a dialog message.
                            showSettingsDialog();
                        }
                    }
  
                    @Override
                    public void onPermissionRationaleShouldBeShown(List<PermissionRequest> list, PermissionToken permissionToken) {
                        // this method is called when user grants some permission and denies some of them.
                        permissionToken.continuePermissionRequest();
                    }
                }).withErrorListener(error -> {
                    // we are displaying a toast message for error message.
                    Toast.makeText(getApplicationContext(), "Error occurred! ", Toast.LENGTH_SHORT).show();
                })
                // below line is use to run the permissions on same thread and to check the permissions
                .onSameThread().check();
    }
  
    // below is the shoe setting dialog method which is use to display a dialogue message.
    private void showSettingsDialog() {
        // we are displaying an alert dialog for permissions
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
  
        // below line is the title for our alert dialog.
        builder.setTitle("Need Permissions");
  
        // below line is our message for our dialog
        builder.setMessage("This app needs permission to use this feature. You can grant them in app settings.");
        builder.setPositiveButton("GOTO SETTINGS", (dialog, which) -> {
            // this method is called on click on positive button and on clicking shit button
            // we are redirecting our user from our app to the settings page of our app.
            dialog.cancel();
            // below is the intent from which we are redirecting our user.
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", getPackageName(), null);
            intent.setData(uri);
            startActivityForResult(intent, 101);
        });
        builder.setNegativeButton("Cancel", (dialog, which) -> {
            // this method is called when user click on negative button.
            dialog.cancel();
        });
        // below line is used to display our dialog
        builder.show();
    }
}


Kotlin




import android.Manifest
import android.app.AlertDialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.karumi.dexter.Dexter
import com.karumi.dexter.MultiplePermissionsReport
import com.karumi.dexter.PermissionToken
import com.karumi.dexter.listener.PermissionRequest
import com.karumi.dexter.listener.multi.MultiplePermissionsListener
  
class MainActivity : AppCompatActivity() {
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // initializing our button and adding on click listener to it.
        val requestPermissionsBtn = findViewById<Button>(R.id.idBtnRequestPermission)
        requestPermissionsBtn.setOnClickListener {
            // inside on click listener calling method to request permission
            requestPermissions()
        }
    }
  
    private fun requestPermissions() {
        // below line is use to request permission in the current activity.
        // this method is use to handle error in runtime permissions
        Dexter.withActivity(this)
            // below line is use to request the number of permissions which are required in our app.
            .withPermissions(Manifest.permission.CAMERA,
                // below is the list of permissions
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.READ_CONTACTS)
            // after adding permissions we are calling an with listener method.
            .withListener(object : MultiplePermissionsListener {
                override fun onPermissionsChecked(multiplePermissionsReport: MultiplePermissionsReport) {
                    // this method is called when all permissions are granted
                    if (multiplePermissionsReport.areAllPermissionsGranted()) {
                        // do you work now
                        Toast.makeText(this@MainActivity, "All the permissions are granted..", Toast.LENGTH_SHORT).show()
                    }
                    // check for permanent denial of any permission
                    if (multiplePermissionsReport.isAnyPermissionPermanentlyDenied) {
                        // permission is denied permanently, we will show user a dialog message.
                        showSettingsDialog()
                    }
                }
  
                override fun onPermissionRationaleShouldBeShown(list: List<PermissionRequest>, permissionToken: PermissionToken) {
                    // this method is called when user grants some permission and denies some of them.
                    permissionToken.continuePermissionRequest()
                }
            }).withErrorListener {
                // we are displaying a toast message for error message.
                Toast.makeText(applicationContext, "Error occurred! ", Toast.LENGTH_SHORT).show()
            }
            // below line is use to run the permissions on same thread and to check the permissions
            .onSameThread().check()
    }
  
    // below is the shoe setting dialog method
    // which is use to display a dialogue message.
    private fun showSettingsDialog() {
        // we are displaying an alert dialog for permissions
        val builder = AlertDialog.Builder(this@MainActivity)
  
        // below line is the title for our alert dialog.
        builder.setTitle("Need Permissions")
  
        // below line is our message for our dialog
        builder.setMessage("This app needs permission to use this feature. You can grant them in app settings.")
        builder.setPositiveButton("GOTO SETTINGS") { dialog, which ->
            // this method is called on click on positive button and on clicking shit button
            // we are redirecting our user from our app to the settings page of our app.
            dialog.cancel()
            // below is the intent from which we are redirecting our user.
            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
            val uri = Uri.fromParts("package", packageName, null)
            intent.data = uri
            startActivityForResult(intent, 101)
        }
        builder.setNegativeButton("Cancel") { dialog, which ->
            // this method is called when user click on negative button.
            dialog.cancel()
        }
        // below line is used to display our dialog
        builder.show()
    }
}


Step 5: Adding the Required Permissions in the Manifest File 

Navigate to the app > AndroidManifest.xml file and add the below permissions to it. 

XML




<!-- Permissions we are requesting from user -->
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>


After adding these permissions to our AndroidManifest.xml file. Now run our app and see the output of the code. 

Output:



Similar Reads

Android Runtime Permissions with Dexter using Android Jetpack Compose
Android applications require the usage of hardware devices within the android applications such as microphones or cameras. For using these devices within any android application. Permissions for using this hardware have to be provided to the application. For giving these permissions to the application runtime permissions are used. Handling permissi
7 min read
Multiple Runtime Permissions in Android with Kotlin using Dexter
From MarshMallow android introduced runtime permissions, we can grant the permissions while using the app, instead of while installing the app. In general, If you want to use a camera or make a call from your app you will ask for the user's permission. There are some predefined functions provided to ask and know that the user has given the permissi
3 min read
How to Request Permissions in Android Application?
Starting from Android 6.0 (API 23), users are not asked for permissions at the time of installation rather developers need to request the permissions at the run time. Only the permissions that are defined in the manifest file can be requested at run time. Types of Permissions 1. Install-Time Permissions: If the Android 5.1.1 (API 22) or lower, the
8 min read
Android Run Time Permissions using Jetpack Compose
There are many features within android applications that require permissions to be granted by the user. For granting these permissions during runtime, runtime permissions are used within android applications. These permissions are called when the user wants to use any specific feature. Before using that feature permission is requested from the user
6 min read
Understanding Self-Downgrading App Permissions in Android 13
Your app can withdraw access to unneeded runtime permissions starting with Android 13. This API enables your program to carry out operations that improve privacy, including the ones listed below: Follow recommended practices for permissions to increase user confidence. You might want to think about displaying a dialogue to the users that lists the
4 min read
Granular Media Permissions in Android 13
If you are developing or upgrading your app for Android 13 then you will need to have allowed the more granular permission which is newly introduced in the Android 13 SDK. Using these new APIs the user will tend to have better control over the data which he/she shares with your app, this is again done keeping privacy in mind. Based on the type of f
4 min read
How to Enable Notification Runtime Permission in Android 13?
Android 13 starts a new realm of new app permissions which are focussed on users' privacy and peace of mind, one of which is the permission to send notifications to the user. Notifications are an integral part of the Android Operating System, but when you have tons of apps installed, then receiving notifications from them starts getting worse. Star
5 min read
File Permissions in Java
Java provides a number of method calls to check and change the permission of a file, such as a read-only file can be changed to have permissions to write. File permissions are required to be changed when the user wants to restrict the operations permissible on a file. For example, file permission can be changed from write to read-only because the u
3 min read
Easy Stylish Chip Button in Bottom Navigation Bar in Android
We all have come across apps that have a Bottom Navigation Bar. Some popular examples include Instagram, Snapchat, etc. In this article, let’s learn how to implement an easy stylish functional Bottom Navigation Bar in the Android app. For Creating a Basic Bottom Navigation bar refer to Bottom Navigation Bar in Android. A sample GIF is given below t
2 min read
How to Add Easy FlipView in Android?
EasyFlipView is an Android library that allows us to easily create a flip view in our android app. We can use this feature in many apps such as the app in which we store the credit or debit card details of the user (the user can easily flip the card to view the CVV of the card). A sample GIF is given below to get an idea about what we are going to
4 min read
Practice Tags :