You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发:如何提取Uri authority字段的首段字符串

功能实现方案

实现思路

  • 首先调用uri.authority获取完整域名段,优先做非空校验避免运行时崩溃
  • 将域名按.字符切割为数组,取数组第一个元素即为目标公司代码
  • 增加异常兜底逻辑,适配域名格式异常的边界场景

基础实现代码

private fun getCode(uri: Uri): String{
    // 获取域名段,为空返回业务自定义默认值即可,这里示例返回空串
    val authority = uri.authority ?: return ""
    // 按.分割域名
    val domainSegments = authority.split(".")
    // 取第一段作为返回值,切割结果为空时返回默认值
    return domainSegments.firstOrNull() ?: ""
}

兼容带端口场景的优化版

如果你的业务场景中域名可能携带端口(例如home.ab.com:8080),可以先移除端口部分再做切割:

private fun getCode(uri: Uri): String{
    val authority = uri.authority ?: return ""
    // 先移除端口后缀
    val domainWithoutPort = authority.substringBefore(":")
    val domainSegments = domainWithoutPort.split(".")
    return domainSegments.firstOrNull() ?: ""
}

效果验证

传入示例Uri.parse("https://home.ab.com")调用该方法,返回结果为home,完全符合需求。

内容的提问来源于stack exchange,提问作者Maria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 16:36:04