Skip to content
Related Articles

Related Articles

Easy Runtime Permissions in Android with Dexter
  • Difficulty Level : Medium
  • Last Updated : 20 Jan, 2021

The runtime permission in Android which introduced in Marshmallow and due to these runtime permissions user can grant permission to the app in runtime, also while writing the code for runtime permissions. Sometimes handling the task of requesting permissions become so difficult and the developer has to write a huge amount of code. So we will see towards 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 app. 

What we are 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 get to see what we are going to build in this article. Note that we are going to implement this project using the Java language. 

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.



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 towards 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

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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>

chevron_right


Step 4: Working with the MainActivity.java file



Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
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.DexterError;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.PermissionRequestErrorListener;
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(new View.OnClickListener() {
            @Override
            public void onClick(View 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.
        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(new PermissionRequestErrorListener() {
            // this method is use to handle error 
            // in runtime permissions
            @Override
            public void onError(DexterError 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", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int 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", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // this method is called when 
                // user click on negative button.
                dialog.cancel();
            }
        });
        // below line is used
        // to display our dialog
        builder.show();
    }
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

<!-- 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"/>

chevron_right


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

Output:


Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :