Reputation: 710
I'm trying to delete files from public directories (Pictures, Movies, Download,...) on external storage. I have found some similar questions on SO but none of the answers works for me.
Here is the code :
File file = new File("/storage/emulated/0/Pictures/IMG_20131107_142745.jpg");
if (file.exists() && file.canWrite()) {
file.delete()
}
The deleted file is effectively no longer visible in my app but i can still see it with MTP on my laptop. However it seems to be a corrupted file and I can't open it. The only way to get rid of it, is to delete the file manually or to reboot the smartphone.
It works perfectly fine on the emulator when I browse the content with the Android Device Monitor
Upvotes: 0
Views: 1243
Reputation: 12674
You need to use MediaScannerConnection
to scan the file:
MediaScannerConnection.scanFile(
context,
new String[]{fileToDelete, fileToAdd},
null, null);
Upvotes: 2
Reputation: 564
try this code after delete..
(for < KITKAT API 14)
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
For >= KITKAT API 14 use below code
MediaScannerConnection.scanFile(this, new String[] { Environment.getExternalStorageDirectory().toString() }, null, new MediaScannerConnection.OnScanCompletedListener() {
/*
* (non-Javadoc)
* @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
*/
public void onScanCompleted(String path, Uri uri)
{
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Upvotes: 1