我正在学习android开发,在java中阅读getExternalStorageDirectory时遇到了一些问题,我已经阅读了https://developer.android.com/reference/android/os/Environment但无法理解,有人可以帮我提供示例代码在爪哇。
3 回答
从文档中您可以看到:
getExternalStoragePublicDirectory(String type)
此方法在 API 级别 29 中已弃用。为了提高用户隐私,不建议直接访问共享/外部存储设备。当应用程序以 Build.VERSION_CODES.Q 为目标时,从此方法返回的路径不再可供应用程序直接访问。通过迁移到Context#getExternalFilesDir(String)、MediaStore 或 Intent#ACTION_OPEN_DOCUMENT等替代方案,应用程序可以继续访问存储在共享/外部存储上的内容 。
不向此函数传递任何参数以将您的目录作为File
对象:
context.getExternalFilesDir();
这里的“上下文”是一个对象,通过this.getContext();
this
是Activity的当前对象。使用时请仔细检查范围。
重要的
访问内部存储,Manifest.permission.WRITE_EXTERNAL_STORAGE
和/或Manifest.permission.READ_EXTERNAL_STORAGE
文件AndroidManifest.xml中需要。
可选信息:
更新
从 Android 11 开始,它不允许在根目录中创建文件夹/文件,但我们仍然可以在公共目录的帮助下管理文件夹分离(它会显示一个已弃用的警告,但它会起作用)
fun getAbsolutePath(context: Context): File {
return File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "{YOUR_FOLDER_NAME}"))
}
现在,使用公共目录路径创建文件
val file = File(getAbsolutePath(requireContext()), "FILENAME.EXTENSION")
年长者
使用此静态方法。目前我没有找到任何合法的方式来做到这一点。所以,我做了这个静态方法来获取 root 或 getAbsolutePath 文件路径。
public static File getAbsoluteDir(Context ctx, String optionalPath) {
String rootPath;
if (optionalPath != null && !optionalPath.equals("")) {
rootPath = ctx.getExternalFilesDir(optionalPath).getAbsolutePath();
} else {
rootPath = ctx.getExternalFilesDir(null).getAbsolutePath();
}
// extraPortion is extra part of file path
String extraPortion = "Android/data/" + BuildConfig.APPLICATION_ID
+ File.separator + "files" + File.separator;
// Remove extraPortion
rootPath = rootPath.replace(extraPortion, "");
return new File(rootPath);
}
使用getExternalFilesDir()
, getExternalCacheDir()
, or getExternalMediaDirs()
(Context 上的方法) 代替Environment.getExternalStorageDirectory()
String root = mContext.getExternalFilesDir(null).getAbsolutePath();
File myDir = new File(root + "/" + mContext.getResources().getString(R.string.app_name) + "_share");
myDir.mkdirs();