Task: I want to delete files from MediaStore
in a background thread, so the user can work with my app while the thread is working.
Problem:
I know that every time when a process finishes, its threads finish their work as well. So, it means that I will not be able to delete all selected files from the MediaStore
, if the user quickly closes the app, thus killing the process.
Possible solution: Do you think is it a good idea to implement that procedure as a separate process(task)? For example, using a Service
.
Code:
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();
UPDATE:
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();
}
}
Thank you!