我找到了有关如何获取所有图像的代码。
有人能告诉我如何在内部存储和外部存储中只获取 .pdf 文件吗?
final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
//Stores all the images from the gallery in Cursor
Cursor cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy);
//Total number of images
int count = cursor.getCount();
//Create an array to store path to all the images
String[] arrPath = new String[count];
for (int i = 0; i < count; i++) {
cursor.moveToPosition(i);
int dataColumnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
//Store the path of the image
arrPath[i]= cursor.getString(dataColumnIndex);
Log.i("PATH", arrPath[i]);
}
Run Code Online (Sandbox Code Playgroud)
可能的解决方案可以转到每个文件夹并检查 .pdf 是否存在,如果是,您可以对该文件执行任何您想做的操作
public void Search_Dir(File dir) {
String pdfPattern = ".pdf";
File FileList[] = dir.listFiles();
if (FileList != null) {
for (int i = 0; i < FileList.length; i++) {
if (FileList[i].isDirectory()) {
Search_Dir(FileList[i]);
} else {
if (FileList[i].getName().endsWith(pdfPattern)){
//here you have that file.
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
和函数调用将是
Search_Dir(Environment.getExternalStorageDirectory());
Run Code Online (Sandbox Code Playgroud)
您应该能够通过 Android 的MediaStore.Files列出所有这些列出所有这些文件,而无需手动浏览设备的所有文件夹。
例如:
String selection = "_data LIKE '%.pdf'"
try (Cursor cursor = getApplicationContext().getContentResolver().query(MediaStore.Files.getContentUri("external"), null, selection, null, "_id DESC")) {
if (cursor== null || cursor.getCount() <= 0 || !cursor.moveToFirst()) {
// this means error, or simply no results found
return;
}
do {
// your logic goes here
} while (cursor.moveToNext());
}
Run Code Online (Sandbox Code Playgroud)
(注意:该主题可能与另一个较旧的问题重复,但它没有公认的答案,因此无法标记它)
| 归档时间: |
|
| 查看次数: |
9522 次 |
| 最近记录: |