我需要一些非常简单的东西 - 我有一个我的应用程序录制的 mp4 文件,我想将其插入 MediaStore 到用户的视频收藏中。这是我的代码,包括处理新的作用域存储的推荐方法:
// fileToExpose is in internal storage with a name like video_1.mp4
fun copyVideoFileToMediaStore(fileToExpose: File, context: Context): Boolean {
val resolver = context.contentResolver
val volume = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) MediaStore.VOLUME_EXTERNAL_PRIMARY else MediaStore.VOLUME_EXTERNAL
val videoCollection = MediaStore.Video.Media.getContentUri(volume)
val videoDetails = ContentValues().apply {
put(MediaStore.Video.Media.DISPLAY_NAME, fileToExpose.name)
put(MediaStore.Video.Media.MIME_TYPE, "video/mp4")
put(MediaStore.Video.Media.TITLE, name)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
put(MediaStore.Video.Media.IS_PENDING, 1)
}
}
val videoContentUri = resolver.insert(videoCollection, videoDetails) ?: return false
resolver.openFileDescriptor(videoContentUri, "w", null).use { pfd ->
pfd ?: return false
fileToExpose.inputStream().use { input ->
FileOutputStream(pfd.fileDescriptor).use { output ->
input.copyTo(output)
}
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
videoDetails.clear()
videoDetails.put(MediaStore.Video.Media.IS_PENDING, 0)
resolver.update(videoContentUri, videoDetails, null, null)
}
return true
}
但是,在此函数之后调用名称为video_1.mp4
变成类似的东西1589077991588.3gp
,所以名称和扩展名都不同(我的设备是Android 9)。MediaStore.MediaColumns.DATA
已弃用。我怎样才能解决这个问题?
聚会迟到了,但只是偶然发现了这个问题,并在这里寻找答案。在尝试时,我想我找到了解决方案:更新MediaStore.Video.Media.DISPLAY_NAME
after插入视频数据就可以了(在 Android 8 上)。
因此,虽然上述代码适用于 Android 10 及更高版本,但对于 Android 9 及更低版本,我添加了在将内容写入流后更新标题的功能。
// [...] example as above, here we are after the `resolver.openFileDescriptor` section
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
videoDetails.clear()
videoDetails.put(MediaStore.Video.Media.IS_PENDING, 0)
resolver.update(videoContentUri, videoDetails, null, null)
} else {
// On Android <= 9 we need to update the display name after writing the data to ensure the DISPLAY_NAME is correctly set
videoDetails.clear()
videoDetails.put(MediaStore.Video.Media.DISPLAY_NAME, fileToExpose.name)
resolver.update(videoContentUri, videoDetails, null, null)
}
因此,在 Android contentResolver.openOutputStream.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)