媒体存储记录在 Android 10 中将图像保存到图片文件夹时未创建

问题描述

所以,我需要将图像保存到图片文件夹。也会有一些子文件夹。但是每次我想保存图像时都会出现此错误

未能创建新的 mediaStore 记录

这是我试过的:

    @RequiresApi(Build.VERSION_CODES.Q)
    @Throws(IOException::class)
    fun saveMediaToStorage(context: Context,bitmap: Bitmap,format: CompressFormat,fName: String,folderName: String,extension: String) {
        //Generating a file name
        val filename = if (fName.contains("png")) fName.replace(".png","") else fName.replace(".jpg","")

        //Output stream
        var fos: OutputStream? = null
        val relativePath = Environment.DIRECTORY_PICTURES + File.separator + folderName

        Log.d(TAG,"saveMediaToStorage: Relative Path: $relativePath")

        //getting the contentResolver
        context.contentResolver?.also { resolver ->

            //Content resolver will process the contentvalues
            val contentValues = ContentValues().apply {

                //putting file information in content values
                put(MediaStore.MediaColumns.disPLAY_NAME,filename)
                put(MediaStore.MediaColumns.MIME_TYPE,"image/$extension")
                put(MediaStore.MediaColumns.RELATIVE_PATH,relativePath)
            }

            //Inserting the contentValues to contentResolver and getting the Uri
            val imageUri= resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues) ?: 
            throw IOException("Failed to create new mediaStore record") // This line is triggering every time

            //opening an outputstream with the Uri that we got
            fos = imageUri.let { resolver.openOutputStream(it) }
        }

        fos?.use {
            //Finally writing the bitmap to the output stream that we opened
            bitmap.compress(format,100,it)
        }
    }

我能理解的是,imageUri 即将为空。但为什么会这样,我很好..

可能是什么原因,我做错的地方.. 任何帮助将不胜感激。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)