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

本文介绍了一种在Android设备上实现图片保存、删除及媒体库更新的方法。包括如何将Bitmap保存为图片文件、删除指定路径的图片,并确保操作后媒体库能够及时反映变更。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

    }

}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值