需要在AndroidManifest.xml的application域中添加以下字段:
android:requestLegacyExternalStorage="true"
AndroidManifest和PermissionHelp运行中都要申请权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
遇到的问题:
同一套代码APP,在Android8以下运行ok, 能够创建目录,生成文件。放到Android11上就返回false
File Root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
if (!Root.exists()) {
Root.mkdir();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdf.format(System.currentTimeMillis());
Log.d("Tina", "initLog");
if (Root.canWrite()) {
Log.d("Tina", "Root.canWrite()");
try {
File logFile = new File(Root, logFileName);
if (!logFile.exists()) {
Log.d("Tina", "logFile.createNewFile(): " + logFile.createNewFile());
}
}
}
查询资料显示Android11不再支持访问外部存储空间:
引用连接
Applications should not directly use this top-level directory, in order to avoid polluting the user’s root namespace. Any files that are private to the application should be placed in a directory returned by Context.getExternalFilesDir, which the system will take care of deleting if the application is uninstalled. Other shared files should be placed in one of the directories returned by getExternalStoragePublicDirectory.
外部存储设备上的应用专用目录
从 Android 11 开始,应用无法在外部存储设备上创建自己的应用专用目录。如需访问系统为您的应用提供的目录,请调用 getExternalFilesDirs()。
故针对Android11以上的访问存储空间需更改为:
File Root;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Root = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
} else {
//此处也可以统一使用上面的目录
Root = Environment.getExternalStorageDirectory();
}