简体   繁体   中英

Android : Delete file from public external storage

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

You need to use MediaScannerConnection to scan the file:

MediaScannerConnection.scanFile(
            context, 
            new String[]{fileToDelete, fileToAdd},
            null, null); 

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);
          }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM