[英]Android : Delete file from public external storage
我正在嘗試從外部存儲上的公共目錄(圖片,電影,下載等)中刪除文件。 我在SO上找到了一些類似的問題,但是沒有一個答案對我有用。
這是代碼:
File file = new File("/storage/emulated/0/Pictures/IMG_20131107_142745.jpg");
if (file.exists() && file.canWrite()) {
file.delete()
}
刪除的文件實際上不再在我的應用程序中可見,但是我仍然可以在筆記本電腦上使用MTP看到它。 但是,它似乎是損壞的文件,我無法打開它。 擺脫它的唯一方法是手動刪除文件或重新啟動智能手機。
當我使用Android設備監視器瀏覽內容時,它在模擬器上可以正常運行
您需要使用MediaScannerConnection
掃描文件:
MediaScannerConnection.scanFile(
context,
new String[]{fileToDelete, fileToAdd},
null, null);
刪除后請嘗試此代碼。
(對於<KITKAT API 14)
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
對於> = 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.