最近项目中需要通过ContentProvider获取某种类型的文件列表进行展示,然后在展示列表中可以对文件进行复制,移动和删除操作。在开发过程中,对文件操作以后,再次拉取列表,发现还是原来的旧数据,数据并没有刷新,于是做了一下追溯和解决。
查询文件
ContentProvider
private List<File> findFile(Context context, List<String> extensions) {
String[] mineTypes = null;
if (extensions != null && !extensions.isEmpty()) {
mineTypes = new String[extensions.size()];
int i = 0;
for (String ext : extensions) {
mineTypes[i++] = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
}
}
final Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
uri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
} else {
uri = MediaStore.Files.getContentUri("external");
}
final String[] projection = new String[]{
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.TITLE,
MediaStore.Files.FileColumns.SIZE,
MediaStore.Files.FileColumns.DATE_MODIFIED,
MediaStore.Files.FileColumns.MIME_TYPE
};
String selection = null;
if (mineTypes != null) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < mineTypes.length; i++) {
builder.append(MediaStore.Files.FileColumns.MIME_TYPE).append(" = ?");
if (i != mineTypes.length - 1) {
builder.append(" OR ");
}
}
selection = builder.toString();
}
final String[] selectionArgs = mineTypes;
final String sortOrder = MediaStore.Files.FileColumns.DATE_MODIFIED + " DESC";
Cursor cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
if (cursor == null) return null;
List<File> files = new ArrayList<>(cursor.getCount());
if (cursor.moveToFirst()) {
do {
final String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA));
final String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.TITLE));
final long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.SIZE));
final long modifiedDate = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATE_MODIFIED));
final String mineType = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.MIME_TYPE));
File file = new File(path);
if (file.exists()) {
files.add(file);
}
} while (cursor.moveToNext());
}
return files;
}
遍历
private List<File> findFile(File file, FileFilter filter) {
List<File> arrays = new ArrayList<>();
File[] files = file.listFiles(filter);
if (files == null || files.length == 0) return arrays;
for (File singleFile : files) {
if (singleFile.isDirectory() && !singleFile.isHidden()) {
arrays.addAll(findFile(singleFile, filter));
} else {
arrays.add(singleFile);
}
}
return arrays;
}
更新媒体库
当某个目录不需要被MediaStore扫描,就在目录下创建一个名为.nomedia的空文件,这样就能阻止媒体扫描程序读取这个目录下的媒体文件。也就无法通过MediaStore分享给其他程序。
广播
private void scanFile(Context context, String filePath) {
final File file = new File(filePath);
if (!file.exists()) return;
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
final Uri contentUri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
contentUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileProvider", file);
} else {
contentUri = Uri.fromFile(file);
}
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
}
MediaScannerConnection
两个方法:
- 非静态方法:public void scanFile(String path, String mimeType)
一次只能扫描一个文件,path必须是一个具体的文件,不能是目录
public class MediaScanner {
private final MediaScannerConnection mConnection;
private final MediaScannerConnection.MediaScannerConnectionClient mClient;
private File mFile = null;
private String mMimeType = null;
public MediaScanner(Context context) {
this.mClient = new MediaScannerClient();
this.mConnection = new MediaScannerConnection(context, this.mClient);
}
public void scanFile(File file, String mineType) {
this.mFile = file;
this.mMimeType = mineType;
this.mConnection.connect();
}
private class MediaScannerClient implements MediaScannerConnection.MediaScannerConnectionClient {
@Override
public void onMediaScannerConnected() {
if (mFile != null) {
scanFile(mFile, mMimeType);
}
}
@Override
public void onScanCompleted(String path, Uri uri) {
mConnection.disconnect();
}
private void scanFile(File file, String mineType) {
if (file.isFile()) {
mConnection.scanFile(file.getAbsolutePath(), mineType);
return;
}
File[] files = file.listFiles();
if (files == null || files.length == 0) {
return;
}
for (File f : files) {
scanFile(f, mineType);
}
}
}
}
- 静态方法:public static void scanFile(Context context, String[] paths, String[] mimeTypes,
OnScanCompletedListener callback) 可以一次传递多个文件,如果mimeTypes不为空,就必须和paths的长度一致。mimeTypes可以为空
final String[] paths = new String[]{file.getAbsolutePath()};
MediaScannerConnection.scanFile(context, paths, null, new MediaScannerConnection.OnScanCompletedListener() {
@Override
public void onScanCompleted(String path, Uri uri) {
}
});
ContentProvider
通过调用ContentResolver的update,insert,delete方法更新。
- update(@RequiresPermission.Write @NonNull Uri uri, @Nullable ContentValues values, @Nullable String where, @Nullable String[] selectionArgs)
- update(@RequiresPermission.Write @NonNull Uri uri, @Nullable ContentValues values, @Nullable Bundle extras)
- insert(@RequiresPermission.Write @NonNull Uri url, @Nullable ContentValues values)
- insert(@RequiresPermission.Write @NonNull Uri url, @Nullable ContentValues values, @Nullable Bundle extras)
- delete(@RequiresPermission.Write @NonNull Uri url, @Nullable String where, @Nullable String[] selectionArgs)
- delete(@RequiresPermission.Write @NonNull Uri url, @Nullable Bundle extras)
- bulkInsert(@RequiresPermission.Write @NonNull Uri url, @NonNull ContentValues[] values)
- applyBatch(@NonNull String authority, @NonNull ArrayList<ContentProviderOperation> operations)
感谢大家的支持,如有错误请指正,如需转载请标明原文出处!
|