我需要一些非常简单的东西 - 我有一个我的应用程序录制的 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
已弃用。我怎样才能解决这个问题?