android10 保存图片到系统相册,刷新媒体库

android9之前,保存图片使用MediaScannerConnection,android10之后,则需要把文件复制到DCIM目录下,虽然android10的方法可以向下兼容,但复制文件效率始终不如刷新媒体库,所以最好是根据SDK_INT选择方法

    //保存图片
    public static void scanFile(File file){
            String mimeType = getMimeType(file);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
            String fileName = file.getName();
            ContentValues values = new ContentValues();
            values.put(MediaStore.MediaColumns.DISPLAY_NAME,fileName);
            values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
            ContentResolver contentResolver = context.getContentResolver();
            Uri uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            if(uri == null){
                ToastUtils.showShort("图片保存失败");
                return;
            }
            try {
                OutputStream out = contentResolver.openOutputStream(uri);
                FileInputStream fis = new FileInputStream(file);
                FileUtils.copy(fis,out);
                fis.close();
                out.close();
                ToastUtils.showShort("图片保存成功");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            MediaScannerConnection.scanFile(Utils.getApp(), new String[]{file.getPath()}, new String[]{mimeType}, (path, uri) -> {
                ToastUtils.showShort("图片已成功保存到" + path);
            });
        }
    }


    public static String getMimeType(File file){
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String type = fileNameMap.getContentTypeFor(file.getName());
        return type;
    }

猜你喜欢

转载自blog.csdn.net/jingzz1/article/details/106272289