android11 存储机制变化之保存图片至图库代码案例

1.首先附上一份android 11存储机制变动简介官方文档供参考

https://developer.android.google.cn/preview/privacy/storage#java

2.参考源码实现的在android11中保存图片到图库的代码:

public void saveImageToGallery2(Context context){
    Long mImageTime = System.currentTimeMillis();
    String imageDate = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date(mImageTime));
    String SCREENSHOT_FILE_NAME_TEMPLATE = "Screenshot_%s.png";//图片名称,以"Screenshot"+时间戳命名
    String mImageFileName = String.format(SCREENSHOT_FILE_NAME_TEMPLATE, imageDate);

    Resources res=getResources();
    Bitmap image =BitmapFactory.decodeResource(res, R.drawable.splash_bg);

    final ContentValues values = new ContentValues();
    values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES
            + File.separator + "dh"); //Environment.DIRECTORY_SCREENSHOTS:截图,图库中显示的文件夹名。"dh"
    values.put(MediaStore.MediaColumns.DISPLAY_NAME, mImageFileName);
    values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
    values.put(MediaStore.MediaColumns.DATE_ADDED, mImageTime / 1000);
    values.put(MediaStore.MediaColumns.DATE_MODIFIED, mImageTime / 1000);
    values.put(MediaStore.MediaColumns.DATE_EXPIRES, (mImageTime + DateUtils.DAY_IN_MILLIS) / 1000);
    values.put(MediaStore.MediaColumns.IS_PENDING, 1);

    ContentResolver resolver = context.getContentResolver();
    final Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    try {
        // First, write the actual data for our screenshot
        try (OutputStream out = resolver.openOutputStream(uri)) {
            if (!image.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                throw new IOException("Failed to compress");
            }
        }
        // Everything went well above, publish it!
        values.clear();
        values.put(MediaStore.MediaColumns.IS_PENDING, 0);
        values.putNull(MediaStore.MediaColumns.DATE_EXPIRES);
        resolver.update(uri, values, null, null);
    }catch (IOException e){
        resolver.delete(uri, null);
        Log.d("Exception",e.toString());
    }
}

 

 

你可能感兴趣的:(android,11,保存图片至图库,存储,图片存储,图片保存)