Android 6.0写入外部SD卡

Anv*_*esh 1 android android-permissions android-6.0-marshmallow

我尝试在Android 6.0上的外部SD卡上写一切,但我无法写上它.

我对stackoverflow进行了研究,发现了很多东西,但都没有.这是我的代码

String extPath = System.getenv("SECONDARY_STORAGE") + "/Android/data/com.gvm.externalstorage.externalstoragetest/";
File file = new File(extPath,"myFiles");

            if (!file.exists()) {
                boolean dirResult = file.mkdirs();
                Log.e("Directory Exist", dirResult + " Directory created");
            } else {
                Log.e("Directory Exist", "Exist");
                Log.e("Direcotry Path",file.getAbsolutePath());
            }
            //String displayname = fileName.replace("%20", " ");
            File outputFile = new File(file, "mytest5.txt");
            outputFile.createNewFile();
Run Code Online (Sandbox Code Playgroud)

此代码适用于Android 5.0,但不适用于Android 6.0.

然后我也尝试了这个路径,这给了我权限错误,我已经为运行时权限设置了所有权限和托管代码.

/mnt/media_rw/6AC9-083B

File write failed: java.io.IOException: open failed: EACCES (Permission denied)
Run Code Online (Sandbox Code Playgroud)

如果有人可以帮助我,那么在过去的3天里我会这样做很棒.

谢谢,Anvesh

Anv*_*esh 8

经过长时间的努力,我找到了解决方案.在Android 6.0中,它总是不会给你SD卡路径:

System.getenv("SECONDARY_STORAGE") 
Run Code Online (Sandbox Code Playgroud)

或这个

Environment.getExternalStorageDirectory()
Run Code Online (Sandbox Code Playgroud)

所以我用这个检索了外部SD卡路径

File[] fs = context.getExternalFilesDirs(null);
            String extPath = "";
            // at index 0 you have the internal storage and at index 1 the real external...
            if (fs != null && fs.length >= 2)
            {
                extPath = fs[1].getAbsolutePath();
                Log.e("SD Path",fs[1].getAbsolutePath());
            }
Run Code Online (Sandbox Code Playgroud)

休息一切都将保持相同的许可和所有.

感谢那些帮助过我的人.