【Android】根据URI获取文件扩展名或MimeType

关于安卓中的URI

安卓中的URI包含多种格式,可以是文件,可以是媒体库资源,可以是Resource

也可以是网络地址,或其它资源标识

这里我们主要针对文件来源的URI

安卓中通过URI访问文件主要包括三种方式

  • 文件路径
  • 媒体库资源(背后仍然是文件,但无法直接访问)
  • Resource资源

对于这三种不同的格式,我们要分别采取不同的解析方式

提取文件扩展名和MimeType
kotlin 复制代码
object UriCompat {

    const val SCHEME_HTTP = "http"
    const val SCHEME_HTTPS = "https"
  
    fun Uri.getExtensionName(): String {
        val context = getAppContext()
        val typeMap = MimeTypeMap.getSingleton()
        when (scheme) {
            ContentResolver.SCHEME_FILE -> {
                val url = Uri.fromFile(File(path)).toString()
                return MimeTypeMap.getFileExtensionFromUrl(url)
            }
            ContentResolver.SCHEME_CONTENT -> {
                val type = context.contentResolver.getType(this)
                return typeMap.getExtensionFromMimeType(type).orEmpty()
            }
            ContentResolver.SCHEME_ANDROID_RESOURCE -> {
                val retriever = MediaMetadataRetriever()
                retriever.setDataSource(context, this)
                val type = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE)
                return typeMap.getExtensionFromMimeType(type).orEmpty()
            }
            SCHEME_HTTP,
            SCHEME_HTTPS -> return ""
            else -> return ""
        }
    }

    fun Uri.getMimeType(): String {
        return MimeTypeMap.getSingleton()
            .getMimeTypeFromExtension(getExtensionName())
            .orEmpty()
    }
}
相关推荐
阿pin11 小时前
Android随笔-kotlin withContext
android·kotlin·withcontext
树码小子12 小时前
开启 IDEA 中的断言功能
android·java·intellij-idea
Kslient12 小时前
HeaderBehavior
android
Android-Flutter13 小时前
android 动画详解
android·kotlin
小孔龙18 小时前
GraphicBuffer 跨进程共享
android
行业研究员19 小时前
Android内置GPS与腾讯地图定位技术对比分析
android·android定位·腾讯地图定位
Android-Flutter20 小时前
android WMS 详解(二)
android·kotlin
游戏开发爱好者820 小时前
App Store 上传 IPA 自动化,.p8 密钥认证与 CI/CD 接入实战
android·运维·ci/cd·小程序·uni-app·自动化·iphone
游戏开发爱好者81 天前
iOS 推送怎么配置,APNs 推送证书、设备库与群发
android·ios·小程序·https·uni-app·iphone·webview
阿pin1 天前
Android随笔-kotlin 高阶函数
android·kotlin·高阶函数