Android Navigation Component 中如何获取跳转至destination的deep-link
获取NavDestination对应Deep Link的实现方案
可以直接通过NavDestination提供的官方API获取Deep Link相关信息,具体实现如下:
- 若需要获取当前目标页所有预配置的Deep Link规则,直接调用
NavDestination的getDeepLinks()方法(Kotlin可直接访问deepLinks属性),返回值为该页面注册的所有NavDeepLink实例集合,可从中提取uri pattern、action、mimeType等配置信息。 - 若需要获取本次导航实际触发使用的Deep Link uri,可以从当前回栈条目的参数中提取,仅当本次导航是通过Deep Link触发时该值存在。
Kotlin 示例代码
navController.addOnDestinationChangedListener { _, destination, _ -> // 获取该目标页所有预配置的Deep Link val allConfiguredDeepLinks = destination.deepLinks allConfiguredDeepLinks.forEach { navDeepLink -> val uriPattern = navDeepLink.uriPattern Log.d("DeepLinkInfo", "配置的Deep Link规则:$uriPattern") } // 获取本次跳转触发用的Deep Link uri(仅Deep Link跳转场景有效) val currentBackStackEntry = navController.currentBackStackEntry val deepLinkIntent = currentBackStackEntry?.arguments?.getParcelable<Intent>( NavController.KEY_DEEP_LINK_INTENT ) deepLinkIntent?.data?.let { triggerUri -> Log.d("DeepLinkInfo", "本次跳转实际使用的uri:$triggerUri") } }
Java 示例代码
navController.addOnDestinationChangedListener((controller, destination, arguments) -> { // 获取该目标页所有预配置的Deep Link List<NavDeepLink> allConfiguredDeepLinks = destination.getDeepLinks(); for (NavDeepLink navDeepLink : allConfiguredDeepLinks) { String uriPattern = navDeepLink.getUriPattern(); Log.d("DeepLinkInfo", "配置的Deep Link规则:" + uriPattern); } // 获取本次跳转触发用的Deep Link uri(仅Deep Link跳转场景有效) NavBackStackEntry currentBackStackEntry = controller.getCurrentBackStackEntry(); if (currentBackStackEntry != null) { Intent deepLinkIntent = currentBackStackEntry.getArguments().getParcelable( NavController.KEY_DEEP_LINK_INTENT ); if (deepLinkIntent != null && deepLinkIntent.getData() != null) { Uri triggerUri = deepLinkIntent.getData(); Log.d("DeepLinkInfo", "本次跳转实际使用的uri:" + triggerUri); } } });
注意:非Deep Link跳转的场景下,
KEY_DEEP_LINK_INTENT对应的参数会为空,此时只能获取到该页面预配置的Deep Link规则,无法拿到实际触发跳转的uri。
内容的提问来源于stack exchange,提问作者mrzbn
相关产品推荐
相关产品推荐

