Duplicate permission request after orientation change

前端 未结 3 1630
耶瑟儿~
耶瑟儿~ 2021-02-07 16:40

Because the Android SDK 23 gives users the possibility to deny apps access to certain functionalities I wanted to update one of my apps to request permissions as it is described

3条回答
  •  萌比男神i
    2021-02-07 17:03

    As CommonsWare said in his comment the best solution is to put a boolean into the savedInstanceState-Bundle to know if the dialog is still open.

    Example:

    // 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;
        }
    }
    

提交回复
热议问题