Reputation: 1679
I know how to get the MIME Type from an URI when the scheme is "content" or "file". However, I cannot find any solution when the scheme is "android.resource". For example, I have res/raw/video.mp4
.
val uri = Uri.parse("android.resource://$packageName/${R.raw.video}")
The uri is good because I can do the following
videoView.setVideoURI(uri)
videoView.start()
Given such an URI, how can I get its mime type (should be "video/mp4" in this case)?
Upvotes: 2
Views: 1367
Reputation: 2672
You can use MediaMetadataRetriever for media file:
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")
For any other type:
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
}
Upvotes: 1