我还没有找到使用显式深层链接的方法,但我选择了一种利用隐式深层链接的解决方案。
首先,在导航图 XML 中添加指向您的片段的深层链接。
<deepLink android:id="@+id/deepLink"
app:uri="my-app://com.example.app/hotspot?ssid={ssid}&passkey={passkey}" />
在清单中的<activity /> 中添加<nav-graph /> 标记。这将确保创建所有意图过滤器并将其合并到您的清单中。
<nav-graph android:value="@navigation/primary_app_nav" />
为通知创建您的PendingIntent,如下所示。
fun getNotificationPendingIntent(ssid: String, passkey: String): PendingIntent {
val uri = Uri.parse("my-app://com.example.app/hotspot?ssid=$ssid&passkey=$passkey")
val bundle = Bundle().apply { putParcelable(SHARE_DEEP_LINK_KEY, uri) }
val intent = Intent(this, SailsActivity::class.java).apply {
putExtras(bundle)
// to clear the back stack
addFlags(FLAG_ACTIVITY_CLEAR_TOP or FLAG_ACTIVITY_SINGLE_TOP
or FLAG_ACTIVITY_CLEAR_TASK or FLAG_ACTIVITY_NEW_TASK)
}
return PendingIntent.getActivity(this, launchShareSheetCode, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
最后,您需要处理来自Activity 类的onCreate() 方法的深层链接意图。
private fun handleDeepLinkIntent() {
val deepLink = intent.extras?.getParcelable(SHARE_DEEP_LINK_KEY) as? Uri
deepLink?.also {
val intent = Intent(this, SenderService::class.java)
this.bindService(intent, serviceConn, Context.BIND_ABOVE_CLIENT)
navigateDeepLink(it)
}
}
private fun navigateDeepLink(uri: Uri) {
findNavController(R.id.navHostFragment).apply {
if (graph.hasDeepLink(uri))
navigate(uri)
else {
currentDestination?.getAction(id)?.let {
navigate(id)
}
}
}
}
深层链接 URI 参数在目标片段中自动可供您使用。
if (arguments != null) {
val ssid = requireArguments().getString("ssid")
val passkey = requireArguments().getString("passkey")
}