[英]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. 我在SO上找到了一些类似的问题,但是没有一个答案对我有用。
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. 删除的文件实际上不再在我的应用程序中可见,但是我仍然可以在笔记本电脑上使用MTP看到它。 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 当我使用Android设备监视器浏览内容时,它在模拟器上可以正常运行
You need to use MediaScannerConnection
to scan the file: 您需要使用MediaScannerConnection
扫描文件:
MediaScannerConnection.scanFile(
context,
new String[]{fileToDelete, fileToAdd},
null, null);
try this code after delete.. 删除后请尝试此代码。
(for < KITKAT API 14) (对于<KITKAT API 14)
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
For >= KITKAT API 14 use below code 对于> = KITKAT API 14,请使用以下代码
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);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.