android – 在方向更改后重复权限请求

前端之家收集整理的这篇文章主要介绍了android – 在方向更改后重复权限请求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
因为 Android SDK 23使用户有可能拒绝应用访问某些功能,所以我想更新我的一个应用程序来请求权限,如下所述: https://developer.android.com/preview/features/runtime-permissions.html.

在其中一个活动中,我嵌入了一个SupportMapFragment.要使其工作,您需要具有WRITE_EXTERNAL_STORAGE权限,因此当我启动导致创建权限请求对话框的活动时,我要求它.

现在的问题是当对话框仍然打开时,我旋转设备,活动将重新启动,并打开一个新的权限请求对话框,而旧的仍然在那里.结果是两个对话框之间的对比,只有一个是有用的.

有没有办法摆脱首先开始的对话框?

解决方法

正如CommonsWare在他的 comment中所说的,最好的解决方案是将一个布尔值放在savedInstanceState-Bundle中,以了解对话框是否仍然打开.

例:

// true if dialog already open
private boolean alreadyAskedForStoragePermission = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(savedInstanceState != null) {
        alreadyAskedForStoragePermission = savedInstanceState.getBoolean(STORAGE_PERMISSION_DIALOG_OPEN_KEY,false);
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    outState.putBoolean(KEY,alreadyAskedForStoragePermission);
}

private void checkStoragePermission(){
    if(alreadyAskedForStoragePermission){
        // don't check again because the dialog is still open
        return;
    }

    if(ActivityCompat.checkSelfPermission(this,STORAGE_PERMISSIONS[0]) != PackageManager.PERMISSION_GRANTED){
        // the dialog will be opened so we have to keep that in memory
        alreadyAskedForStoragePermission = true;
        ActivityCompat.requestPermissions(this,STORAGE_PERMISSIONS,STORAGE_PERMISSION_REQUEST_CODE);
    } else {
        onStoragePermissionGranted();
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,@NonNull String[] permissions,@NonNull int[] grantResults) {
    switch (requestCode){
        case STORAGE_PERMISSION_REQUEST_CODE:
            // the request returned a result so the dialog is closed
            alreadyAskedForStoragePermission = false;

            if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
                onStoragePermissionGranted();
            }

            break;
    }
}

猜你在找的Android相关文章