gpt4 book ai didi

android - 如何使用 scheme == "android.resource"从 URI 获取 MIME 类型

转载 作者:行者123 更新时间:2023-11-29 01:00:11 28 4
gpt4 key购买 nike

当方案为“内容”或"file"时,我知道如何从 URI 获取 MIME 类型。但是,当方案为“android.resource”时,我找不到任何解决方案。例如,我有 res/raw/video.mp4

val uri = Uri.parse("android.resource://$packageName/${R.raw.video}")

uri 很好,因为我可以执行以下操作

videoView.setVideoURI(uri)
videoView.start()

给定这样一个 URI,我怎样才能得到它的 mime 类型(在这种情况下应该是“video/mp4”)?

最佳答案

您可以使用 MediaMetadataRetriever对于媒体文件:

val uri = Uri.parse("android.resource://$context.packageName/${R.raw.video}")
val retriever = MediaMetadataRetriever()
val mimeType = try {
retriever.setDataSource(context, uri)
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE)
} catch (e: Exception) {
null
}
Log.d(TAG, "MIME type: $mimeType")

对于任何其他类型:

val resId = R.raw.video
val resUri = Uri.parse("android.resource://${context.packageName}/$resId")

val mimeType = tryGetMediaMimetype(context, resUri)
?: tryGetImageMimetype(context.resources, resId)
?: tryGetMimeTypeFromExtension(context.resources, resId)
Log.d(TAG, "MIME type: $mimeType")

...

fun tryGetMediaMimetype(context: Context, uri: Uri): String? {
val retriever = MediaMetadataRetriever()
return try {
retriever.setDataSource(context, uri)
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE)
} catch (e: Exception) {
null
}
}

fun tryGetImageMimetype(resource: Resources, resId: Int): String? {
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
return try {
BitmapFactory.decodeResource(resource, resId, options)
options.outMimeType
} catch (e: OutOfMemoryError) {
return null
}
}

fun tryGetMimeTypeFromExtension(resource: Resources, resId: Int): String? {
val value = TypedValue()
resource.getValue(resId, value, true)
val fileName = value.string.toString()

val dotIndex = fileName.lastIndexOf(".")
val extension = if (dotIndex >= 0) {
fileName.substring(dotIndex + 1)
} else null

return if (extension != null) {
MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)
} else null
}

关于android - 如何使用 scheme == "android.resource"从 URI 获取 MIME 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51792770/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com