[英]How to read or write file as getExternalStorageDirectory is deprecated in API 29?
I am learning android development and i am facing some problem to read getExternalStorageDirectory in java, I have read https://developer.android.com/reference/android/os/Environment but can't understand, can someone help me with example code在 java 中。
从文档中您可以看到:
getExternalStoragePublicDirectory(String type)
此方法在 API 级别 29 中已弃用。为了提高用户隐私,不推荐直接访问共享/外部存储设备。 当应用以 Build.VERSION_CODES.Q 为目标时,应用无法再直接访问从此方法返回的路径。 通过迁移到Context#getExternalFilesDir(String)、MediaStore 或 Intent#ACTION_OPEN_DOCUMENT等替代方案,应用程序可以继续访问存储在共享/外部存储上的内容。
不将任何参数作为参数传递给此函数,以将您的目录作为File
对象:
context.getExternalFilesDir();
这里的“Context”是一个通过this.getContext();
获取的对象this.getContext();
this
是 Activity 的当前对象。 使用时请仔细检查示波器。
重要的
要访问内部存储, AndroidManifest.xml文件中需要Manifest.permission.WRITE_EXTERNAL_STORAGE
和/或Manifest.permission.READ_EXTERNAL_STORAGE
。
可选信息:
使用这个静态方法。 目前我没有找到任何合法的方法来做到这一点。 所以,我使用这个静态方法来获取 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()
或getExternalMediaDirs()
(上下文方法)而不是Environment.getExternalStorageDirectory()
String root = mContext.getExternalFilesDir(null).getAbsolutePath();
File myDir = new File(root + "/" + mContext.getResources().getString(R.string.app_name) + "_share");
myDir.mkdirs();
简短答案:
String path = getContext().getExternalFilesDir(null).getAbsolutePath();
在2022年,不推荐使用Environment.getExternalStorageDirectory
和Environment.getExternalStoragePublicDirectory
。
从 API 29 ~ 31 开始,它们已被标记为已弃用,但不在上面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.