项目场景:
如果你的app下的build.gradle设置了compileSdkVersion 30,且targetSdkVersion 30。你测试手机刚好是Android 11的。如果文件根目录还是Environment.getExternalStorageDirectory()就会创建失败。
log错误提示:
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)
不用去看是否是读写权限问题,Android 11根本没有这目录了
解决方案:
方式一:把compileSdkVersion和targetSdkVersion降到29以下(我没测,理论上可以)
方式二:加版本判断获取根目录
public static String getSDPath(Context context) {
File sdDir = null;
boolean sdCardExist = Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
if (sdCardExist) {
if (Build.VERSION.SDK_INT>=29){
sdDir = context.getExternalFilesDir(null);
}else {
sdDir = Environment.getExternalStorageDirectory();
}
} else {
sdDir = Environment.getRootDirectory();
}
return sdDir.toString();
}
|