gpt4 book ai didi

Android 在外部 SD 卡上写入文件,适用于 Android 5+

转载 作者:搜寻专家 更新时间:2023-11-01 07:49:32 24 4
gpt4 key购买 nike

我无法将文件写入外部 SD 卡。 我收到 EAcess 被拒绝的错误消息。我在互联网上搜索了很多,发现从 Android 4.4 + android 的存储访问框架 (SAF) 开始需要写入文件。

但我正在使用一些能够在 SD 卡上写入(创建/删除/重命名)文件的 android 应用程序。他们没有使用 SAF。

所以请帮助我如何在不使用 SAF 框架的情况下做到这一点。

谢谢

最佳答案

关于Android的外部存储器有很多困惑。它实际上并不指向Removable SD MICRO CARD。那么,谷歌认为“外部存储器”是什么意思

引用Android API Document

Every Android-compatible device supports a shared "external storage" that you can use to save files. This can be a removable storage media (such as an SD card) or an internal (non-removable) storage. Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer.

事实是 Environment.getExternalStorageDirectory() 和 Context.getExternalFilesDirs() 可以返回位于内部存储中的模拟外部内存。因此,这些函数本身不会给出预期的结果。 SECONDARY_STORAGE 环境变量可以帮助获取可移动内存的真实路径,但由于 OEM 实现,不允许在其根目录上写入。在这种情况下,我们应该尝试通过 Context.getExternalFilesDirs() 或 ContextCompat.getExternalFilesDirs() 获取允许读写应用数据文件的应用数据文件夹。

我用下面的方法解决了我的问题,请检查一下,希望它能帮助你解决问题。

@TargetApi(Build.VERSION_CODES.KITKAT)
private String getRemovablePath(){
String secondaryStore = System.getenv("SECONDARY_STORAGE");
if (secondaryStore != null){
secondaryStore = secondaryStore.split(":")[0];
secondaryStore += File.separator + "Backups/";
File file = new File(secondaryStore);
if((file.mkdir() || file.isDirectory()) && isFileWritable(secondaryStore)){
return secondaryStore;
} else {
secondaryStore = null;
}
}

// try again by fix address
if(secondaryStore == null){
if (new File("/Removable/MicroSD/").exists()){
secondaryStore = "/Removable/MicroSD/";
} else if( new File("/storage/extSdCard/").exists()){
secondaryStore = "/storage/extSdCard/";
} else if( new File("/storage/sdcard1/").exists()){
secondaryStore = "/storage/sdcard1/";
} else if( new File("/storage/usbcard1/").exists()){
secondaryStore = "/storage/usbcard1/";
} else if( new File("/storage/external_SD/").exists()){
secondaryStore = "/storage/external_SD/";
}
/** add more fix addresses you know */
secondaryStore += "Backups/";
File file = new File(secondaryStore);
if((file.mkdir() || file.isDirectory()) && isFileWritable(secondaryStore)){
return secondaryStore;
} else {
secondaryStore = null;
}

}
/** Try data folder*/
if(secondaryStore == null){
int ver = Build.VERSION.SDK_INT;
File[] externalRoots = null;
if(ver <= Build.VERSION_CODES.JELLY_BEAN_MR2){
externalRoots = ContextCompat.getExternalFilesDirs(getBaseContext(), null);
} else {
externalRoots = getExternalFilesDirs(null);
}

if(externalRoots.length > 1){
secondaryStore = externalRoots[1].getAbsolutePath() + File.separator;
return secondaryStore;
} else {
secondaryStore = null;
}
}


return secondaryStore;
}

关于Android 在外部 SD 卡上写入文件,适用于 Android 5+,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37009655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com