首页 > 解决方案 > 无法获得android 11中存储目录的运行时权限

问题描述

我的项目存储目录:/storage/emulated/0/Android/data/myprojectapp

问题:我要在运行时获取我的项目目录的存储访问权限

在 AndroidManifest.xml 中添加了下面提到的权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

检查运行时权限的代码

@Override
    public void onCreate(Bundle savedInstanceState){
        Log.d(TAG, "onCreate() [IN]");
        super.onCreate(savedInstanceState);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    PERMISSION_READ_EXTERNAL_STORAGE_CONSTANT);
        } else {
            setMainActivity();
        }
        
    }

@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
                                           @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_READ_EXTERNAL_STORAGE_CONSTANT: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 &&
                        grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d(TAG, "permission granted"); // able to see this is the log as permission granted
                    setMainActivity();
                } else {
                    Toast.makeText(this, "Need sdcard permissions", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

//After the permssion is granted in runtime below mentioned method is called
 private void setMainActivity() {
    static final String PKGPUSH_DIR = "/storage/emulated/0/Android/data/myprojectapp";
   //checking whether the  is writable or not
        File directory = new File(Constants.PKGPUSH_DIR);
        if(directory.canWrite()){
            Log.i(TAG, "set as writable "+directory);
        }else{
            Log.i(TAG, "Set as not writable"); // always it return the log as set as not writable
        }  


 }

首先,在授予运行时权限后没有创建目录有人能告诉我为什么即使在授予运行时权限之后也没有创建目录以及为什么它不能访问?

是因为 Android 11 范围存储更改:

defaultConfig { applicationId "myprojectapp" minSdkVersion 26 targetSdkVersion 30 }

标签: runtime-permissionsandroid-11scoped-storage

解决方案


推荐阅读