如何解决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 举报,一经查实,本站将立刻删除。