如何在Android的assetlinks.json中匹配复杂深度链接URL模式?
关于assetlinks.json的relation字段与复杂URL匹配方案
一、relation字段的可选值
除了你用到的delegate_permission/common.handle_all_urls,常见的官方预定义值还有:
delegate_permission/common.get_login_creds:用于网站与应用间的登录凭证共享关联delegate_permission/common.verify_email:用于邮箱验证场景的网站-应用关联- 自定义关系字符串:你可以自定义任意字符串(比如
myapp.handle_project_urls),但这仅用于标识关联类型,不会直接影响URL匹配逻辑,核心的URL路由规则仍需在应用侧处理。
二、实现复杂URL匹配的解决方案
assetlinks.json仅负责完成网站与应用的身份绑定,不处理URL路径过滤。要实现「匹配https://server.example.com/project/*但排除/project/upload」的需求,有两种可行方案:
方案1:intent-filter结合应用侧逻辑过滤
- 在AndroidManifest中配置基础的前缀匹配:
<intent-filter android:autoVerify="true"> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="https" android:host="server.example.com" android:pathPrefix="/project/" /> </intent-filter>
- 在处理深度链接的Activity中添加排除逻辑:
class DeepLinkActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) intent.data?.let { uri -> val path = uri.path ?: "" // 排除指定路径 if (path == "/project/upload") { // 跳转回浏览器处理该链接 val browserIntent = Intent(Intent.ACTION_VIEW, uri) startActivity(browserIntent) finish() return } // 处理符合要求的深度链接 handleValidDeepLink(uri) } finish() } private fun handleValidDeepLink(uri: Uri) { // 你的业务逻辑实现 } }
该方案兼容所有Android版本,是最通用的处理方式。
方案2:Android12+适配pathAdvancedPattern(兼容低版本)
针对Android12及以上系统,可直接用android:pathAdvancedPattern配置正则排除规则,同时为低版本保留方案1的代码逻辑:
<intent-filter android:autoVerify="true"> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="https" android:host="server.example.com" android:pathAdvancedPattern="/project/(?!upload).*" /> </intent-filter>
低版本系统会忽略pathAdvancedPattern,仍走pathPrefix匹配,此时通过应用侧代码排除即可。
关键说明
assetlinks.json的核心作用是让系统信任你的应用可处理对应网站的链接,不参与URL路径的具体匹配,路径规则由应用的intent-filter和代码逻辑共同决定。
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

