Android Deleting Files MediaScannerConnection

2019-08-03 08:33发布

问题:

I'm trying to delete some files or directories from the internal memory (ASUS TF101) using the commands File.delete(). However, using the Android File explorer I can see how the files are removed, but using the Windows explorer they still show there.

I solved a similar issue when adding files just creating a MediaScannerConection (and using the method scanFile).

Does anyone know how to solve this problem? Of course it´s not acceptable to restart the device as the final user will not like this "solution".

回答1:

See the answer of manisha in this thread: Android file delete leaves empty placeholder in Gallery

In my case, it worked fine because i was saving a photo and then scanning it using the MediaScannerConnection, so when the scan finishes i have the URI of that file and then i can use the following code whitout problems.

getContentResolver().delete(imageUri, null, null);

Hope this works for you. This seems to be more suitable than forcing a SD Card remount by sending an intent to android system.



回答2:

I had the same problem, but I found the answear:

Android uses a media table to handle files. When you make changes to a file, you must update this table.

Try this:

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));

Google doc: http://developer.android.com/reference/android/content/Intent.html#ACTION_MEDIA_MOUNTED