How do I get the MIME Type from a URI with scheme == “android.resource”

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



How do I get the MIME Type from a URI with scheme == “android.resource”



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.


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)?





I do not think that is possible, sorry.
– CommonsWare
Aug 10 at 21:38




1 Answer
1



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






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard