无法将图像保存到画廊

Cant save image to gallery

我正在尝试使用 MediaStore 将位图作为图像保存到 phone 存储中,如下所示:

 MediaStore.Images.Media.insertImage(contentResolver, bitmap, "title" , "description")

图像没有保存在设备存储中,我已经在模拟器和物理设备上检查过。


到目前为止我做了什么:


我知道我可以在不使用 MediaStore 的情况下保存图像,如 this thread 中所述,但我想知道我在这里做错了什么以及为什么我不能将位图保存为图像设备存储。

我试过了,但对我也不起作用。所以我使用了 Android 下载管理器,它简单易行;-)

这是代码

/*
This method can be used to download an image from the internet using a url in Android. This use Android Download Manager to
download the file and added it to the Gallery. Downloaded image will be saved to "Pictures"
Folder in your internal storage
*/

private void downloadImageNew(String filename, String downloadUrlOfImage){
    try{
        DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        Uri downloadUri = Uri.parse(downloadUrlOfImage);
        DownloadManager.Request request = new DownloadManager.Request(downloadUri);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
                .setAllowedOverRoaming(false)
                .setTitle(filename)
                .setMimeType("image/jpeg") // Your file type. You can use this code to download other file types also.
                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                .setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES,File.separator + filename + ".jpg");
        dm.enqueue(request);
        Toast.makeText(this, "Image download started.", Toast.LENGTH_SHORT).show();
    }catch (Exception e){
        Toast.makeText(this, "Image download failed.", Toast.LENGTH_SHORT).show();
    }
}

出于某种原因,即使在授予 WRITE_EXTERNAL_STORAGE 之后,在查看日志后我发现我收到了这个错误:

Permission Denial: writing com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=11218, uid=10079 requires android.permission.WRITE_EXTERNAL_STORAGE, or grantUriPermission()

我觉得这很奇怪,因为我在将图像保存到图库之前检查过是否已授予此权限。

我的解决方法是删除应用程序并重新安装