DontPanic
DontPanic

Reputation: 2406

requestPermission: How to wait until granted?

Android API 23 and above requires that "dangerous" permissions be confirmed at run-time. In accordance with other StackOverflow suggestions, I check for required permissions using checkSelfPermissions() and if required, call requestPermissions(). That works fine, but the request is handled asynchronously, i.e., requestPermissions() returns immediately. The problem is that my app goes on its merry way after requestPermissions(). Sometime later, the permission confirm dialog(s) appear but by that time, my app has tried API calls that fail.

I assume I need to wait until all permissions have been granted before proceeding in my app. I guess I could implement some polling kluge to do this but that's just too crude for me. What is the "Best Practice" to get around this? Various Best Practice descriptions in the documentation do not address this issue.

Upvotes: 4

Views: 6579

Answers (1)

TheWanderer
TheWanderer

Reputation: 17824

Put your logic in its own function(s), outside of onCreate().

private void doStuff() {
    //whatever
}

If the permissions are granted, just call that function directly from onCreate():

@Override
public void onCreate(Bundle savedInstanceState) {
    //...
    if (checkSelfPermissions(/*whatever*/) {
        doStuff();
    } else {
        requestPermissions(/*whatever*/);
    }

    //nothing dependent on runtime permissions after this point
}

Then override onRequestPermissionsResult():

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == /*whatever you set in requestPermissions()*/) {
        if (!Arrays.asList(grantResults).contains(PackageManager.PERMISSION_DENIED)) {
            //all permissions have been granted
            doStuff(); //call your dependent logic
        }
    }
}

Upvotes: 10

Related Questions