android刪除手機(jī)照片

:項(xiàng)目開發(fā)中,臨時用到,總結(jié)的。沒有做深入學(xué)習(xí),先寫出來,記錄一下。

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()方法 你應(yīng)該知道 是刪除的意思;
        } else if (file.isDirectory()) { // 否則如果它是一個目錄
            File files[] = file.listFiles(); // 聲明目錄下所有的文件 files[];
            for (int i = 0; i < files.length; i++) { // 遍歷目錄下所有的文件
                deleteFile(files[i]); // 把每個文件 用這個方法進(jìn)行迭代
            }
        }
        file.delete();
    }
}

在app中刪除手機(jī)中的圖片,如果使用file的delete方法,會出現(xiàn)刪除不干凈的情況,這個時候留有一個空白的文件,還是會顯示在相冊中。經(jīng)過調(diào)查后,發(fā)現(xiàn)是數(shù)據(jù)庫中沒有更新導(dǎo)致的,后來經(jīng)過測試多款機(jī)型,找到了一個比較好的方法,代碼如下:

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為圖片路徑,這樣刪除以后,在有的機(jī)型里還會有殘留,所以需要更新媒體庫。代碼如下:

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

但是敲的時候才發(fā)現(xiàn),沒有MediaScanner類。而是MediaScannerConnection

public static void updateMediaStore(final  Context context, final String path) {
    //版本號的判斷  4.4為分水嶺,發(fā)送廣播更新媒體庫
    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())));
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容