Use-Case:
Here, I can create and save files in local storage using MediaStore and get all the files from MediaStore. But Once I clear-storage or reinstall the app, the files will no longer be available which was self-created by that same app. Do we need permission to read the self-created files once the app is reinstalled?
If we need permission, how to ask permission and get all that PDF files from that Downloads folder in Android-Q.
public static ArrayList<FileModel> getExternalPDFFileList(Context context) {
ArrayList<FileModel> uriList = new ArrayList<>();
try {
ContentResolver cr = context.getContentResolver();
String[] projection = {MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DISPLAY_NAME};
String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE;
String[] selectionArgs = null;
String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
String[] selectionArgsPdf = new String[]{mimeType};
String sortOrder = android.provider.MediaStore.Files.FileColumns.DATE_TAKEN + " DESC";
Cursor cursor = cr.query(extUri, projection, selectionMimeType, selectionArgsPdf, sortOrder + " DESC");
assert cursor != null;
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
int columnIndex = cursor.getColumnIndex(projection[0]);
long fileId = cursor.getLong(columnIndex);
Uri fileUri = Uri.parse(extUri.toString() + "/" + fileId);
String displayName = cursor.getString(cursor.getColumnIndex(projection[1]));
uriList.add(new FileModel(displayName, fileUri));
}
cursor.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return uriList;
}
Note: Before android Q, we can get all the files of the external storage once the permission is enabled. But after Android SDK-28, there is completely different file-system. Due to lack of proper documentation it is difficult to do minor task.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…