Android技术知识Android知识Android开发

android删除手机照片

2017-09-21  本文已影响0人  DaZenD

:项目开发中,临时用到,总结的。没有做深入学习,先写出来,记录一下。

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())));
    }
}
上一篇 下一篇

猜你喜欢

热点阅读