[英]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.