【发布时间】:2017-06-21 12:29:11
【问题描述】:
任务:我想在后台线程中从MediaStore 中删除文件,以便用户可以在线程工作时使用我的应用程序。
问题:
我知道每当一个进程完成时,它的线程也会完成它们的工作。因此,这意味着如果用户快速关闭应用程序,我将无法从MediaStore 中删除所有选定的文件,从而终止进程。
可能的解决方案:您认为将该过程作为一个单独的流程(任务)来实现是个好主意吗?例如,使用Service。
代码:
Snackbar.make(findViewById(R.id.rootView),message)
.setAction("UNDO", new View.OnClickListener() {
@Override
public void onClick(View view) {
//restore data
}
})
.addCallback(new BaseTransientBottomBar.BaseCallback<Snackbar>() {
@Override
public void onDismissed(Snackbar transientBottomBar, int event) {
super.onDismissed(transientBottomBar, event);
switch (event) {
case DISMISS_EVENT_SWIPE:
case DISMISS_EVENT_TIMEOUT:
//delete the files using either a background thread, or a separate task
break;
}
}
})
.show();
更新:
public static void deleteFile(Context context, File mediaFile) {
if(!mediaFile.delete()) {
Log.e(TAG, "Cannot delete file "+ mediaFile.getAbsoluteFile());
}
String[] projection = { MediaStore.Images.Media._ID };
String selection = MediaStore.Images.Media.DATA + " = ?";
String[] selectionArgs = new String[] { mediaFile.getAbsolutePath() };
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
if(cursor!=null) {
if (cursor.moveToFirst()) {
long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
Uri deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
contentResolver.delete(deleteUri, null, null);
}
cursor.close();
}
}
谢谢!
【问题讨论】:
-
有多少个文件?这个过程需要很长时间?
-
视情况而定。它可以是 10 或 1000。基本上,用户可以删除整个文件夹的文件。
-
删除1000个文件需要很长时间吗?特别是放在一个文件夹里。我猜您不仅要删除
MediaStore,还要更新MediaStore。 -
够用了。如果我想删除 1000 个文件,然后我立即关闭应用程序,它将删除大约 10-20 个文件。
-
是的,没错,我也在更新
MediaStore。我现在将发布此过程的代码。
标签: android multithreading service android-asynctask mediastore