Wait for user permission

AsfK picture AsfK · May 30, 2016 · Viewed 30.2k times · Source

I building an application that sampling GPS on starting. As you probably know, permissions are requested during run-time from Android M and above.

So, in my case I'm starting with checking if permissions are needed, like this:

private void permissionForAndroidM()
{
    if (Build.VERSION.SDK_INT > 22) {
        String[] allPermissionNeeded = {
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO};

        List<String> permissionNeeded = new ArrayList<>();
        for (String permission : allPermissionNeeded)
            if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED)
                permissionNeeded.add(permission);
        if (permissionNeeded.size() > 0) {
            requestPermissions(permissionNeeded.toArray(new String[0]), 0);
        }
    }
}

but Android continuing running the code and asking for GPS data ( = crash, because the user didn't accept the permission request).

I find many solutions about waiting for user input (like using DialogInterface.OnClickListener, link, but it's cannot implemented in this case, because I'm not creating the dialog).

Bottom line, the question: How can I wait for user answer from the Android permission dialog ?

Answer

Valentin Yuryev picture Valentin Yuryev · May 30, 2016

You can handle user response overriding method

public void onRequestPermissionsResult(
    int requestCode,
    String[] permissions,
    int[] grantResults
)

from your activity.