这篇文章上次修改于 502 天前,可能其部分内容已经发生变化,如有疑问可询问作者。

Android 访问 /storage/emulated/0 Permission denied 的问题

要想读写 /storage/emulated/0 需要做到如下几点:

  • 在清单文件 AndroidManifest.xml 文件中增加:

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  • 手动请求权限

    private static final int REQUEST_PERMISSION_CODE = 1;    
    private void requestPermissions() {
        int permission_write = ContextCompat.checkSelfPermission(MainActivity.this,
                                                                 Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int permission_read = ContextCompat.checkSelfPermission(MainActivity.this,
                                                                Manifest.permission.READ_EXTERNAL_STORAGE);
        if (permission_read != PackageManager.PERMISSION_GRANTED ||
            permission_write != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE,              Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_CODE);
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_PERMISSION_CODE) {
    
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
  • 在清单文件中 application 标签增加属性:

    android:requestLegacyExternalStorage="true"

参考资料