Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 413
DontPanic Avatar asked Oct 20 '25 20:10

DontPanic


1 Answers

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
        }
    }
}
like image 172
TheWanderer Avatar answered Oct 23 '25 11:10

TheWanderer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!