Android M 写入 SD 卡 - 权限被拒绝

标签 android android-6.0-marshmallow

我正在尝试将文件从我的应用程序中复制到 SD 卡,但我收到错误 eacces (permission denied)。操作系统是 Android M,我已经允许运行时存储权限(在应用程序信息中检查)。我还在 AndroidManifest.xml 中设置了使用权限

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

如果我复制到 SD 卡就不起作用

Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/1032-2568/SomeFolder/
Error: java.io.FileNotFoundException: /storage/1032-2568/SomeFolder/SomeFile.txt: open failed: EACCES (Permission denied)

如果我复制到内部存储就可以使用

Source: data/user/0/com.example.myapp/cache/SomeFile.txt
Destination: /storage/emulated/0/SomeFolder/

将文件从源复制到目标的代码

/*
 * Below are the parameters I have tried
 *
 * inputPath - data/user/0/com.example.myapp/cache or data/user/0/com.example.myapp/cache/
 * inputFile - /SomeFile.txt or SomeFile.txt
 * outputPath - /storage/1032-2568/SomeFolder/ or /storage/1032-2568/SomeFolder
 */
public static void copyFile(String inputPath, String inputFile, String outputPath) {

    InputStream in = null;
    OutputStream out = null;
    try {

        //create output directory if it doesn't exist
        File dir = new File (outputPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        in = new FileInputStream(inputPath + inputFile);
        out = new FileOutputStream(outputPath + inputFile);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();


        // write the output file (You have now copied the file)
        out.flush();
        out.close();
    }
    catch (FileNotFoundException fnfe1) {
        /* I get the error here */
        Log.e("tag", fnfe1.getMessage());
    }
    catch (Exception e) {
        Log.e("tag", e.getMessage());
    }
}

ES 文件资源管理器

我看到 ES File Explorer 也无法在 Redmi 设备的 SD 卡上写入任何内容。 Here's a video with solution .按照适用于我设备上的 ES Explorer 的步骤操作。这可以通过编程方式完成吗?

最佳答案

正如@CommonsWare 在这里所建议的,我们必须使用 android 提供的新存储访问框架,并且必须获得用户的许可才能写入 SD 卡文件,正如您所说,这已经写入文件管理器应用程序 ES 文件资源管理器中。

这是让用户选择“SD卡”的代码:

startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), requestCode);

看起来有点像这样:

enter image description here

并在 pickedDir 中获取文档路径并在您的 copyFile block 中进一步传递 并使用此路径写入文件:

public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    if (resultCode != RESULT_OK)
        return;
    else {
        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);
        copyFile(sdCard.toString(), "/File.txt", path + "/new", pickedDir);
    }
}


public void copyFile(String inputPath, String inputFile, String outputPath, DocumentFile pickedDir) {

    InputStream in = null;
    OutputStream out = null;
    try {

        //create output directory if it doesn't exist
        File dir = new File(outputPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        in = new FileInputStream(inputPath + inputFile);
        //out = new FileOutputStream(outputPath + inputFile);

        DocumentFile file = pickedDir.createFile("//MIME type", outputPath);
        out = getContentResolver().openOutputStream(file.getUri());

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();


        // write the output file (You have now copied the file)
        out.flush();
        out.close();
    } catch (FileNotFoundException fnfe1) {
    /* I get the error here */
        Log.e("tag", fnfe1.getMessage());
    } catch (Exception e) {
        Log.e("tag", e.getMessage());
    }
}

关于Android M 写入 SD 卡 - 权限被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43066117/

相关文章:

android - 带有 compileSdkVersion 23 的 APK,无法在带有 APK 22 的 Android 手机中打开主要 Activity

java - listFiles() 在/storage/emulated 上返回 null,而/storage/emulated/0 存在

java - 如何在Android中创建目录?

javascript - 如何在 Android 中突破 Twitter 应用内浏览器?

android - 如何判断图像何时被剪裁?

android - 找不到符号变量 SEND_SMS

android - 棉花糖权限应该仅在尚未授予时询问

安卓棉花糖 : Changing permissions at run time crashes app

java - Volley 响应无法将数据存储到对象java android

android - 如何在 Android 中保存音乐播放器应用程序的 "now playing"列表?