android 手机图片生成删除不能及时看到效果问题

1.保存图片的方法

public static StringSaveImage(Bitmap finalBitmap,String filename) {

String path="";

    String root = Environment.getExternalStorageDirectory().toString();

    File myDir =new File(root +"/xqFile");

    myDir.mkdirs();

    String fname = filename;

    File file =new File (myDir, fname);

    if (file.exists ()) file.delete ();

    try {

file.createNewFile();

        path=file.getAbsolutePath();

        FileOutputStream out =new FileOutputStream(file);

        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);

        out.flush();

        out.close();

    }catch (Exception e) {

e.printStackTrace();

    }

return path;

}

这样图片可以保存,但是有得机型在文件夹下不能及时看到生成图片。这种现象是少了给手机媒体库通知造成的。

2.删除图片

public static void deleteFile(String fileurl)throws Exception{

File dir =new File(fileurl);

    if (dir.isFile())

dir.delete();

}

这种方法删除图片,发现在有的机型还是能看到,改用以下方法删除图片

public static void deleteImageMedia(final Context context,String filePath){

Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

    ContentResolver mContentResolver = context.getContentResolver();

    String where = MediaStore.Images.Media.DATA +"='" + filePath +"'";

    //删除图片

    mContentResolver.delete(uri, where, null);

}

以上方法能正常删除,但是发现删除了,有的机型还是能看到。这种问题也会缺少给媒体库发送通知

3.给媒体库发送通知

可以在生成图片或者删除图片以后加上以下方法

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

    }

}

加上以上方法发现可以正常看到生成图片,删除的图片也及时消失了

你可能感兴趣的:(android 手机图片生成删除不能及时看到效果问题)