在Android 11中,DocumentFile的findFile()方法变慢的原因是由于在Android 11中引入了Scoped Storage的限制。为了解决这个问题,可以使用以下方法:
方法1:使用Storage Access Framework
Uri treeUri = DocumentsContract.buildTreeDocumentUri(
"com.your.app", "com.your.app.documents");
DocumentFile pickedDir = DocumentFile.fromTreeUri(context, treeUri);
DocumentFile file = pickedDir.findFile("filename.txt");
在上面的示例中,我们使用Storage Access Framework来获取文件的Uri,并通过DocumentFile.fromTreeUri()方法获取目录的DocumentFile对象。然后,我们可以使用findFile()方法来查找特定的文件。
方法2:使用ContentResolver查询文件
Uri collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
String[] projection = new String[]{
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DISPLAY_NAME
};
String selection = MediaStore.Files.FileColumns.DISPLAY_NAME + "=?";
String[] selectionArgs = new String[]{"filename.txt"};
String sortOrder = null;
try (Cursor cursor = context.getContentResolver().query(
collection,
projection,
selection,
selectionArgs,
sortOrder
)) {
if (cursor != null && cursor.moveToFirst()) {
long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Files.FileColumns._ID));
Uri uri = ContentUris.withAppendedId(collection, id);
// 这里可以使用uri来操作文件
}
}
在上面的示例中,我们使用ContentResolver来查询匹配的文件。我们使用MediaStore.Files.getContentUri()方法获取文件的Uri,然后使用ContentResolver.query()方法查询匹配的文件。通过Cursor对象,我们可以获取文件的Uri,并进行相关操作。
这些方法可以绕过DocumentFile的findFile()方法的性能问题,以实现更快速的文件查找。
下一篇:Android 11包可见性问题