Request permission dialog pauses my activity

后端 未结 3 1006
隐瞒了意图╮
隐瞒了意图╮ 2021-01-22 15:47

I am asking for permission inside onActivityResult of my activity and what is happening is that my activity is being paused while request permission dialog is disp

相关标签:
3条回答
  • 2021-01-22 16:13

    what is happening is that my activity is being paused while request permission dialog is displayed. Why is that?

    requestPermissions docs says

    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[]).

    Although an another solution is move your code in onStop if possible and suitable

    0 讨论(0)
  • 2021-01-22 16:20

    There is also possibility that, your Activity (say, MainActivity) that invoking the

    requestPermissions()
    

    might have been declared flag

    android:noHistory="true" 
    

    in the Manifest.

    Therefore the MainActivity is paused, and eventually finish()'d during requestPermissions(). From Android documentation requestPermissions

    You cannot request a permission if your activity sets noHistory to true in the manifest

    If that is the case.. you may do a finish() clear specific activity programmatically inside the MainActivity { .. } to remove it from the activities stack, not in the Manifest.

    This was in my case !

    0 讨论(0)
  • 2021-01-22 16:26

    Source code of method Activity#requestPermissions:

    public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
        if (requestCode < 0) {
            throw new IllegalArgumentException("requestCode should be >= 0");
        }
        if (mHasCurrentPermissionsRequest) {
            Log.w(TAG, "Can reqeust only one set of permissions at a time");
            // Dispatch the callback with empty arrays which means a cancellation.
            onRequestPermissionsResult(requestCode, new String[0], new int[0]);
            return;
        }
        Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
        startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null);
        mHasCurrentPermissionsRequest = true;
    }
    

    We can clearly see that a new activity is opened. Hence onPause in the calling activity will be surely called. So this is the expected behavior.

    If you want to prevent pausing your activity, make sure you already have the required permissions before opening that activity.

    If your activity is main activity, add an splash activity. Otherwise check for permissions before opening your activity.

    0 讨论(0)
提交回复
热议问题