在后台线程中删除文件

Delete files in a background thread

任务:我想在后台线程中从 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();
    }
}

谢谢!

是的,这听起来很适合 Service ,但是 当你说“作为一个单独的过程(任务)”时,这不是 Service 是:

A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.

A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).

https://developer.android.com/reference/android/app/Service.html#WhatIsAService

之所以可行,是因为用户通常不会以终止进程的方式关闭应用程序。应用程序继续 运行,即使所有活动都已关闭,甚至从最近使用的应用程序列表中删除也是如此。