使用SAF(存储访问框架)的Android SD卡写权限

时间:2016-04-26 10:46:56

标签: android android-5.0-lollipop android-sdcard storage-access-framework documentfile

关于如何在SD卡(android 5及以上版本)中编写(和重命名)文件的大量调查结果后,我认为android提供的新SAF需要获得用户写入SD卡文件的许可。

我在此文件管理器应用程序 ES文件资源管理器中看到,最初它采用以下方式获取读写权限,如图所示。

enter image description here

Picture 2

选择SD卡后,授予写入权限。

因此我以同样的方式尝试使用SAF,但在重命名文件时失败了。我的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    rename = (Button) findViewById(R.id.rename);

    startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), 42);
}

@Override
public void onActivityResult(int requestCode,int resultCode,Intent resultData) {
    if (resultCode != RESULT_OK)
        return;
    Uri treeUri = resultData.getData();
    DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
    grantUriPermission(getPackageName(), treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}

public void renameclick(View v) {
    File ff = new File("/storage/sdcard1/try1.jpg");
    try {
        ff.createNewFile();
    } catch (Exception e) {
        Log.d("error", "creating");
        e.printStackTrace();
    }
}

在运行代码后,我仍然拒绝EAacces权限。

1 个答案:

答案 0 :(得分:20)

让用户选择" SD卡"甚至是"内部存储" SAF root允许您的应用程序访问相应的存储,但只能通过SAF API访问,而不能直接通过文件系统访问。例如,您可以将代码翻译成以下内容:

public void writeFile(DocumentFile pickedDir) {
    try {
        DocumentFile file = pickedDir.createFile("image/jpeg", "try2.jpg");
        OutputStream out = getContentResolver().openOutputStream(file.getUri());
        try {

            // write the image content

        } finally {
            out.close();
        }

    } catch (IOException e) {
        throw new RuntimeException("Something went wrong : " + e.getMessage(), e);
    }
}

在Android的最新版本中,使用java.io.File访问应用程序外部的数据几乎完全弃用。

相关问题