問題場(chǎng)景:
如果你的app下的build.gradle設(shè)置了compileSdkVersion 30费变,且targetSdkVersion 30灾而。你測(cè)試手機(jī)剛好是Android 11的。如果文件根目錄還是Environment.getExternalStorageDirectory()就會(huì)創(chuàng)建失敗昼激。
log錯(cuò)誤提示:
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/Starwberry/img/local_sendpic_temp.jpg: open failed: ENOENT (No such file or directory)
不用去看是否是讀寫權(quán)限問題锡搜,Android 11根本沒有這目錄了
解決方案:
方式一:把compileSdkVersion和targetSdkVersion降到29以下(我沒測(cè),理論上可以)
方式二:加版本判斷獲取根目錄
public static String getSDPath(Context context) {
File sdDir = null;
boolean sdCardExist = Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);// 判斷sd卡是否存在
if (sdCardExist) {
if (Build.VERSION.SDK_INT>=29){
//Android10之后
sdDir = context.getExternalFilesDir(null);
}else {
sdDir = Environment.getExternalStorageDirectory();// 獲取SD卡根目錄
}
} else {
sdDir = Environment.getRootDirectory();// 獲取跟目錄
}
return sdDir.toString();
}