Checking if permissions have been granted already by user in Android
Asked Answered
L

4

33

I have defined all the dangerous permissions in a String array as below:

String[] perms = {Manifest.permission.READ_CONTACTS,
                      Manifest.permission.READ_PHONE_STATE,
                      Manifest.permission.CALL_PHONE,
                      Manifest.permission.MODIFY_PHONE_STATE};

Then to check if they have been granted I run this:

for (int i = 0; i < perms.length; i++) {
        if(ContextCompat.checkSelfPermission(this,perms[i])!=PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this,perms, permsRequestCode);
            break;
        }
    }

For some reason this does not work. It asks for permission once, and then if I manually disable it from settings, it brings up the dialog box more than once.

How do I fix this?

Ludwick answered 9/2, 2017 at 17:35 Comment(1)
Not a single answer referenced the documentation, maybe because it previously did not exist. It is here if you wanted the authoritative docs.Doelling
H
32

As far as I know, this should be working. But you can try using the following function that works. It has a different method than yours.

String requiredPermission = android.Manifest.permission.READ_CONTACTS;
int checkVal = getContext().checkCallingOrSelfPermission(requiredPermission);

Now you can check:

if (checkVal==PackageManager.PERMISSION_GRANTED){}
Hurdygurdy answered 9/2, 2017 at 17:46 Comment(3)
Instead of setting requiredPermission to a string literal, I would recommend setting it to Manifest.permission.READ_CONTACTSStylite
whats the reason of recommending it?Atrium
@Stylite what if someone wants to check permission that Manifest.permission doesn't have, like "com.qualcomm.permission..."Michaelemichaelina
S
29

Use this to check any permissions you want, either single or multiple permissions at once.

public class PermissionsUtils {

public static final int REQUEST_PERMISSION_MULTIPLE = 0;
public static final int REQUEST_PERMISSION_CAMERA = 1;
public static final int REQUEST_PERMISSION_LOCATION = 2;
public static final int REQUEST_WRITE_EXTERNAL = 3;

public static boolean checkAndRequestPermissions(Activity activity) {
    System.out.println("PermissionsUtils checkAndRequestPermissions()");

    int permissionCamera = ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA);
    int permissionLocation = ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION);
    int permissionWriteExternal = ContextCompat.checkSelfPermission(activity,
            Manifest.permission.WRITE_EXTERNAL_STORAGE);

    // Permission List
    List<String> listPermissionsNeeded = new ArrayList<>();

    // Camera Permission
    if (permissionCamera != PackageManager.PERMISSION_GRANTED) {
        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA)) {
            Toast.makeText(activity, "Camera Permission is required for this app to run", Toast.LENGTH_SHORT)
                    .show();
        }
        listPermissionsNeeded.add(Manifest.permission.CAMERA);
    }

    // Read/Write Permission
    if (permissionWriteExternal != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    // Location Permission
    if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
    }

    if (!listPermissionsNeeded.isEmpty()) {
        ActivityCompat.requestPermissions(activity,
                listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
                REQUEST_PERMISSION_MULTIPLE);
        return false;
    }

    return true;
}

/**
 * Requests the Camera permission. If the permission has been denied
 * previously, a SnackBar will prompt the user to grant the permission,
 * otherwise it is requested directly.
 */
public static void requestCameraPermission(Activity activity) {
    // Here, thisActivity is the current activity
    // System.out.println("requestCameraPermission() INITIAL");
    // Toast.makeText(this, "requestCameraPermission() INITIAL",
    // Toast.LENGTH_LONG).show();
    if (ContextCompat.checkSelfPermission(activity,
            Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA)) {
            // Toast.makeText(activity, "Camera permission is
            // needed for this app to run ",
            // Toast.LENGTH_SHORT).show();
            // System.out.println("requestCameraPermission() SHOW INFO");

            // Show an explanation to the user *asynchronously* -- don't
            // block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.
            ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.CAMERA },
                    REQUEST_PERMISSION_CAMERA);

        } else {
            // No explanation needed, we can request the permission.
            // System.out.println("requestCameraPermission() ASK
            // PERMISSION");

            ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.CAMERA },
                    REQUEST_PERMISSION_CAMERA);
        }
        // Permission is granted
    } else {
        System.out.println("requestCameraPermission() PERMISSION ALREADY GRANTED");

    }

}

public static void requestLocationPermission(Activity activity) {
    if (ContextCompat.checkSelfPermission(activity,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            Toast.makeText(activity, "LOCATION permission is needed to display location info ", Toast.LENGTH_SHORT)
                    .show();
            // Show an explanation to the user *asynchronously* -- don't
            // block this thread waiting for the user's response! After the
            // user sees the explanation, try again to request the
            // permission.
            ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                    REQUEST_PERMISSION_LOCATION);

            Toast.makeText(activity, "REQUEST LOCATION PERMISSION", Toast.LENGTH_LONG).show();

        } else {
            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                    REQUEST_PERMISSION_LOCATION);
            Toast.makeText(activity, "REQUEST LOCATION PERMISSION", Toast.LENGTH_LONG).show();
            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
        // Permission is granted
    } else {

    }
}

public static void requestWriteExternalPermission(Activity activity) {
    if (ContextCompat.checkSelfPermission(activity,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            Toast.makeText(activity, "Write permission is needed to create Excel file ", Toast.LENGTH_SHORT).show();
            // Show an explanation to the user *asynchronously* -- don't
            // block this thread waiting for the user's response! After the
            // user sees the explanation, try again to request the
            // permission.
            ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                    REQUEST_WRITE_EXTERNAL);

            Toast.makeText(activity, "REQUEST LOCATION PERMISSION", Toast.LENGTH_LONG).show();

        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                    REQUEST_WRITE_EXTERNAL);

        }
    }
}

public static boolean hasPermissions(Context context, String... permissions) {
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}

}

Sargent answered 9/2, 2017 at 17:50 Comment(1)
@mahdiazarm. How is this out of topic? checkSelfPermission(activity, Manifest.permission.X) checks if any permission is already granted, if you check out other answers they do the same, and rest of the code asks for the permissions not granted.Sargent
P
1

Try by adding perms inside String[]{} it works for me..

for (int i = 0; i < perms.length; i++) {
        if(ContextCompat.checkSelfPermission(this,perms[i])!=PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this,String[]{perms}, permsRequestCode);
            break;
        }
    }
Ply answered 8/1, 2019 at 20:22 Comment(0)
M
0

I've come up with the below helper function, that checks a set of necessary permission and returns false is all are not allowed


fun Activity.hasAllPermissionGranted(): Boolean{
    var allPermissionProvided = true
    
    val requiredPermissions = listOf(Manifest.permission.CAMERA,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.RECORD_AUDIO)
    for (perm in requiredPermissions){

        val checkVal = checkCallingOrSelfPermission(perm)

        if (checkVal!= PackageManager.PERMISSION_GRANTED){
            allPermissionProvided = false
            break;
        }
    }
    return allPermissionProvided
}

And use it anywhere inside an activity like below


class SplashActivity : Activty() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        

        //force user for all permission if not given
       if(!hasAllPermissionGranted(){       
    }

  }

}
Mandie answered 10/7, 2023 at 12:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.