为什么在API 29上图片保存不再起作用了?

4
在我的应用程序中,用户可以通过点击“下载”按钮将图片库中的图像保存到本地设备。该代码在旧设备上可以正常工作,但在API 29上有以下行为:在保存时,我尝试打开画廊查看发生了什么:画廊会更新,一个空图像出现并立即消失一秒钟。我收到通知,图片已保存,但它不会出现,甚至不会在设备浏览器中显示。
//DEXTER HERE  
Picasso.get().load(dummyimage.getLarge()).placeholder(R.drawable.ic_img_error).error(R.drawable.ic_red).into(saveImageToDirectory);


  final Target saveImageToDirectory = new Target() {
        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            ProgressDialog mydialog = new ProgressDialog(getActivity());
            mydialog.setMessage("saving Image to phone");
            mydialog.show();

            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());

            try {
                String fileName = "myApp_" + timeStamp + ".JPG";
                String dirName= "/myApp";
                File file = new File(requireActivity().getApplicationContext().getExternalFilesDir(null).getAbsolutePath() + dirName, fileName);

                //new File(path for the file to be saved, saving file name)
                if (!file.exists()) {
                    //check if the file already exist or if not create a new file
                    //if exist the file will be overwritten with the new image
                    File filedirectory = new File(requireActivity().getApplicationContext().getExternalFilesDir(null).getAbsolutePath()  + dirName);
                    filedirectory.mkdirs();


                }
                if (file.exists()) {
                    file.delete();
                }
                FileOutputStream ostream = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
                Toast.makeText(getActivity(), "Picture saved to Gallery" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                ostream.close();
                mydialog.dismiss();

                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.TITLE, "My Images");
                values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
                values.put(MediaStore.MediaColumns.RELATIVE_PATH,"/myApp");
                // API LEVEL Q: values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
                values.put("_data", file.getAbsolutePath());
                ContentResolver cr = getActivity().getContentResolver();
                cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            } catch (Exception e) {
                mydialog.dismiss();
                Log.e("file creation error", e.toString());
            }

        }

        @Override
        public void onBitmapFailed(Exception e, Drawable errorDrawable) {
        }
        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
        }
    };

由于您可能已经看到,我们使用了 <\/p> 代替


File filedirectory = new File(Environment.getExternalStorageDirectory() + dirName);

我已经在使用

File filedirectory = new File(requireActivity().getApplicationContext().getExternalFilesDir(null).getAbsolutePath()  + dirName);

希望这不是问题,但我遇到了一些奇怪的行为。

这是我的Logcat中得到的错误:

E/file creation error: java.lang.IllegalArgumentException: 主目录(无效)不允许使用content://media/external/images/media;允许的目录为[DCIM,Pictures]

PS:我正在使用Dexter来避免权限问题。

1个回答

2

试试这个

private Uri saveImage(Context context, Bitmap bitmap, @NonNull String folderName, @NonNull String fileName) throws IOException
{
    OutputStream fos;
    File imageFile = null;
    Uri imageUri = null;


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        ContentResolver resolver = context.getContentResolver();
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
        contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM" + File.separator + folderName);
        imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        fos = resolver.openOutputStream(imageUri);
    } else {
        String imagesDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DCIM).toString() + File.separator + folderName;
        imageFile = new File(imagesDir);
        if (!imageFile.exists()) {
            imageFile.mkdir();
        }
        imageFile = new File(imagesDir, fileName + ".png");
        fos = new FileOutputStream(imageFile);
    }

    boolean saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
    fos.flush();
    fos.close();

    if (imageFile != null)  // pre Q
    {
        MediaScannerConnection.scanFile(context, new String[]{imageFile.toString()}, null, null);
        imageUri = Uri.fromFile(imageFile);
    }

    return imageUri;
}

在您的清单文件中添加requestLegacyExternalStorage。
<application
    android:allowBackup="true"
    android:icon="@drawable/icon"
    android:requestLegacyExternalStorage="true"
    android:label="@string/app_name"
    android:roundIcon="@drawable/icon"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    ...
    ...
    ...

</application>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接