在Android 11中,Google引入了一项新的权限策略,称为"Scoped Storage"。这导致了一些应用程序无法访问外部存储中的文件。因此,如果您的应用程序需要访问外部存储中的文件,请使用以下代码:
1.在AndroidManifest.xml中添加以下代码:
2.在应用程序代码中添加以下代码:
// For Android 11 and higher devices, we need to use different approach if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { if (Environment.isExternalStorageManager()) { // Access files here } else { // Request for permission Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION); Uri uri = Uri.fromParts("package", getPackageName(), null); intent.setData(uri); startActivity(intent); } }else{ // Pre Android 11 devices // Access files here }
这段代码检查当前设备的Android版本。如果设备使用的是Android 11及更高版本,则使用新的Scoped Storage策略,并根据是否具有适当的权限来决定是否访问文件。如果没有权限,则请求用户授权。对于早期版本的Android,您可以像往常一样访问文件。