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

标签 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 权限被拒绝。

最佳答案

让用户选择“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 访问应用程序外部的数据几乎已被完全弃用。

关于使用 SAF(存储访问框架)的 Android SD 卡写入权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36862675/

相关文章:

android - fragment 选项卡中的框架布局

Android map 路线叠加示例

android - ubuntu16.04 lts build android5.0 报错

android - 将附件添加到电子邮件

java - file.getName() 什么都不返回

java - 将自定义 Java 数据模型传递到我的 native 代码

android - 使用两个点值的向量在 Android 5.0.1 和 5.0.2 上崩溃?

Android L SoundPool.load() 回归

android - 无法推送选择 : Read-only file system : while moving to SdCard

android - 单击按钮一次打开文件夹(SD 卡)中的所有图像