記:項目開發中,臨時用到,總結的。沒有做深入學習,先寫出來,記錄一下。
public void deletePhotoWithPath(String path) {
if (path != null && path.length() > 0) {
File file = new File(path);
}
}
public void deleteFile(File file) {
if (file.exists()) { // 判斷文件是否存在
if (file.isFile()) { // 判斷是否是文件
file.delete(); // delete()方法 你應該知道 是刪除的意思;
} else if (file.isDirectory()) { // 否則如果它是一個目錄
File files[] = file.listFiles(); // 聲明目錄下所有的文件 files[];
for (int i = 0; i < files.length; i++) { // 遍歷目錄下所有的文件
deleteFile(files[i]); // 把每個文件 用這個方法進行迭代
}
}
file.delete();
}
}
在app中刪除手機中的圖片,如果使用file的delete方法,會出現刪除不干凈的情況,這個時候留有一個空白的文件,還是會顯示在相冊中。經過調查后,發現是數據庫中沒有更新導致的,后來經過測試多款機型,找到了一個比較好的方法,代碼如下:
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver mContentResolver = context.getContentResolver();
String where = MediaStore.Images.Media.DATA + "='" + filePath + "'";
//刪除圖片
mContentResolver.delete(uri, where, null);
其中,filepath為圖片路徑,這樣刪除以后,在有的機型里還會有殘留,所以需要更新媒體庫。代碼如下:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
new MediaScanner(PreviewActivity.this, path);
} else {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
但是敲的時候才發現,沒有MediaScanner類。而是MediaScannerConnection
public static void updateMediaStore(final Context context, final String path) {
//版本號的判斷 4.4為分水嶺,發送廣播更新媒體庫
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
MediaScannerConnection.scanFile(context, new String[]{path}, null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(uri);
context.sendBroadcast(mediaScanIntent);
}
});
} else {
File file = new File(path);
String relationDir = file.getParent();
File file1 = new File(relationDir);
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.fromFile(file1.getAbsoluteFile())));
}
}