Requesting Android M permissions from Activity with noHistory=“true” and/or showOnLockScreen=“true”

Deadly 提交于 2019-12-03 15:10:56

From the documentation for requestPermission() (ActivityCompat):

This method may start an activity allowing the user to choose which permissions to grant and which to reject. Hence, you should be prepared that your activity may be paused and resumed. Further, granting some permissions may require a restart of you application. In such a case, the system will recreate the activity stack before delivering the result to your onRequestPermissionsResult( int, String[], int[]).

I ended up creating a state variable to deal with this, so that onPause() and onResume() can differentiate between being called as a result of a permission request and being called because of other system events.

So something like this:

private final int STATE_STARTING = 0;
private final int STATE_RUNNING = 1;
private final int STATE_REQUESTING_FINE_LOCATION_PERMISSION = 2;

private int state = STATE_STARTING;

@Override
public void onCreate() {
    super.onCreate();
    switch (state) {
        case STATE_STARTING:
            // do your initialization
            state = STATE_RUNNING;
            break;
    }
}

@Override
public void onResume() {
    super.onResume();
    switch (state) {
        case STATE_RUNNING:
            // handle other system events
            break;
        case STATE_REQUESTING_FINE_LOCATION_PERMISSION:
            // handle permission request event
            break;
    }
}

@Override
public void onPause() {
    super.onPause();
    switch (state) {
        case STATE_RUNNING:
            // handle other system events
            break;
        case STATE_REQUESTING_FINE_LOCATION_PERMISSION:
            // handle permission request event
            break;
    }
}

private void someFunction() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        state = STATE_REQUESTING_FINE_LOCATION_PERMISSION;
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_PERMISSION_FINE_LOCATION);
    } else {
        doProcessingRequiringFineLocationPermission();
    }

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case REQUEST_CODE_PERMISSION_FINE_LOCATION:
            if (grantResults != null && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                doProcessingRequiringFineLocationPermission();
            }
            state = STATE_RUNNING;
            break;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!