在Android 11中,应用的文件访问权限得到了加强,因此在访问外部存储器中的文件时,需要使用特定的方法来处理。以下是一个示例代码来读取外部存储上的文件:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
&& Environment.isExternalStorageManager()) {
// Use the MediaStore API to read the file
Uri uri = MediaStore.Downloads.EXTERNAL_CONTENT_URI.buildUpon().appendPath(filename).build();
ContentResolver contentResolver = getContentResolver();
String[] projection = {MediaStore.Downloads._ID, MediaStore.Downloads.DISPLAY_NAME,
MediaStore.Downloads.SIZE};
try (Cursor cursor = contentResolver.query(uri, projection, null, null, null)) {
int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Downloads._ID);
int nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Downloads.DISPLAY_NAME);
int sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Downloads.SIZE);
if (cursor.moveToFirst()) {
Log.d(TAG, "Found file " + cursor.getString(nameColumn) + " with size " +
cursor.getInt(sizeColumn));
// Use the content resolver to open a stream to read the file
try (InputStream is = contentResolver.openInputStream(uri)) {
// Read the file as needed...
} catch (IOException e) {
Log.e(TAG, "Failed to read file", e);
}
} else {
Log.e(TAG, "File not found");
}
} catch (Exception e) {
Log.e(TAG, "Failed to retrieve file", e);
}
} else {
// Use legacy methods to read the file
// For example, use the File API to open a FileInputStream
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
try (FileInputStream is = new FileInputStream(file)) {
// Read the file as needed...
} catch (IOException e) {
Log.e(TAG, "Failed to read file", e);
}
}
在使用MediaStore API时,需要请求用户授予应用访问外部存储器的权限,并且需要检查用户是否已经开启了外部存储器管理器的权限。如果用户未开启该权限,需要通过应用引导用户进行设置。
上一篇:Android11中BroadcastReceiverACTION_SHUTDOWNIntent不起作用的问题
下一篇:Android11中出现“java.io.IOException:NosuchdeviceError”错误提示。