Android将媒体保存到Gallery MediaStoreApi

问题描述

我正在使用此代码通过MediaStoreApi将文件保存到图库。它在Android api级别29和更高版本上运行良好,但是在android api级别28和更低版本上失败。在较低版本上使用MediaStoreApi有什么解决方案?预先感谢!

val values = ContentValues().apply {
    val folderName = if (isVideo) {
        Environment.DIRECTORY_MOVIES
    } else {
        Environment.DIRECTORY_PICTURES
    }
    put(MediaStore.Images.Media.DISPLAY_NAME,fileName)
    put(MediaStore.Images.Media.MIME_TYPE,MimeUtils.guessMimeTypeFromExtension(getExtension(fileName)))
        put(MediaStore.Images.Media.RELATIVE_PATH,folderName + "/${context.getString(R.string.app_name)}/")
        put(MediaStore.Images.Media.IS_PENDING,1)
}

val collection = if (isVideo) {
    MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
} else {
    MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
}
val fileUri = context.contentResolver.insert(collection,values) ?: return

if (isVideo) {
    context.contentResolver.openFileDescriptor(fileUri,"w").use { descriptor ->
        descriptor?.let {
            FileOutputStream(descriptor.fileDescriptor).use { out ->
                val videoFile = File(filePath)
                FileInputStream(videoFile).use { inputStream ->
                    val buf = ByteArray(8192)
                    while (true) {
                        val sz = inputStream.read(buf)
                        if (sz <= 0) break
                        out.write(buf,sz)
                    }
                }
            }
        }
    }
} else {
    context.contentResolver.openOutputStream(fileUri).use { out ->
        val bmOptions = BitmapFactory.Options()
        val bmp = BitmapFactory.decodeFile(filePath,bmOptions)
        bmp.compress(Bitmap.CompressFormat.JPEG,90,out)
        bmp.recycle()
    }
}
values.clear()
values.put(if (isVideo) MediaStore.Video.Media.IS_PENDING else MediaStore.Images.Media.IS_PENDING,0)
context.contentResolver.update(fileUri,values,null,null)

解决方法

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

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...