起因:從Android Q開始,出于資料隱私問題,Android 希望禁止應用程式操作非沙箱內的資料(即使你的應用程式獲取了讀寫存盤卡權限,也不能讀寫非沙盒路徑下的資料),但也提供了requestLegacyExternalStorage機制,來幫助應用使用原來的機制繼續讀寫存盤卡,此機制用于過度期間的,所以臨時解決方法:
>: 應用程式有存盤卡讀寫權限,且在AndroidManifest.xml的application標簽中設定requestLegacyExternalStorage=true,才能訪問,
<application
...
android:requestLegacyExternalStorage="true"
...
>
關聯問題:
問題1. Environment.getExternalStorageDirectory() 過期問題(在Android SDK 29及以上廢棄)
解決:
// 目標SD路徑:/storage/emulated/0
public static String getSDPath(Context context){
String sdPath = "";
boolean isSDExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); //判斷SD卡是否存在
if (isSDExist) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
File externalFileRootDir = context.getExternalFilesDir(Environment.MEDIA_MOUNTED);
do {
externalFileRootDir = Objects.requireNonNull(externalFileRootDir).getParentFile();
} while (Objects.requireNonNull(externalFileRootDir).getAbsolutePath().contains("/Android"));
sdPath = Objects.requireNonNull(externalFileRootDir).getAbsolutePath();
} else {
sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
}
} else {
sdPath = Environment.getRootDirectory().toString();//獲取跟目錄
}
return sdPath;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/342248.html
標籤:其他
