【Android】MediaStore三种刷新方式简介

本文介绍了Android中MediaStore的三种刷新方式:1) 使用MediaStore内部类插入图片;2) 发送ACTION_MEDIA_SCANNER_SCAN_FILE广播更新;3) 通过MediaScannerConnection的scanFile方法批量扫描。此外,还提到了避免目录被扫描的方法——创建.nomedia文件。
摘要由CSDN通过智能技术生成

1、Media是MediaStore的内部类

(MediaStore.Image.Media),它提供了几个insertImage方法,以方便我们想MediaStore插入图片数据,该操作会生成一张缩略图。插入有两个重载方法,一个是传入图片路径,一个是传入Bitmap;

区别:

传入图片路径的方法,会将制定的图片拷贝一份到Picture目录下,也就是SDCARD中共有两种相同的图片。

传入Bitmap的方法,会将图片直接保存到Picture目录下。

/**
 * Insert an image and create a thumbnail for it.
 *
 * @param cr The content resolver to use
 * @param imagePath The path to the image to insert
 * @param name The name of the image
 * @param description The description of the image
 * @return The URL to the newly created image
 * @throws FileNotFoundException
 */
public static final String insertImage(ContentResolver cr, String imagePath,
        String name, String description) throws FileNotFoundException {
   
    // Check if file exists with a FileInputStream
 FileInputStream stream = new FileInputStream(imagePath);
    try {
   
        Bitmap bm = BitmapFactory.decodeFile(imagePath);
        String ret = insertImage(cr, bm, name, description);
        bm.recycle();
        return ret;
    } finally {
   
        try {
   
            stream.close();
        } catch (IOException e) {
   
        }
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 中,我们可以使用以下代码通知相册更新文件夹: ```java String filePath = "/sdcard/image.jpg"; File file = new File(filePath); Uri uri = Uri.fromFile(file); Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri); sendBroadcast(intent); ``` 其中,`filePath` 是要通知相册更新的文件路径。 需要注意的是,Android 10 及以上版本需要使用 `MediaStore` API 进行媒体文件的访问,不能直接使用文件路径。可以使用以下代码通知相册更新: ```java String filePath = "/sdcard/image.jpg"; ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.DISPLAY_NAME, "image.jpg"); values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES); Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); OutputStream outputStream = getContentResolver().openOutputStream(uri); InputStream inputStream = new FileInputStream(filePath); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, length); } outputStream.close(); inputStream.close(); Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri); sendBroadcast(intent); ``` 其中,`filePath` 是要保存到相册的文件路径,`MediaStore.Images.Media.DISPLAY_NAME` 是文件名,`MediaStore.Images.Media.MIME_TYPE` 是文件类型,`MediaStore.Images.Media.RELATIVE_PATH` 是文件保存的相对路径,可以根据需要修改。保存后,使用 `Intent.ACTION_MEDIA_SCANNER_SCAN_FILE` 通知相册更新。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值