首页 > 解决方案 > 支持导航组件的隐式和显式深度链接

问题描述

我正在使用导航组件,并且当用户点击通知时,我试图触发指向特定目的地的显式深度链接,由片段表示。

根据文档,可以像这样创建待处理的意图:

val bundle = bundleOf("id" to "1234")

val pendingIntent = NavDeepLinkBuilder(context)
    .setGraph(R.navigation.nav_graph)
    .setDestination(R.id.myDestination)
    .setArguments(args)
    .createPendingIntent()

其中 nav_graph 定义如下:

<fragment 
   android:id="@+id/myDestination"
   android:name="MyFragment">

   <argument
      android:name="id"
      app:argType="string" />

   <deepLink app:uri="myApp://myFragment?id={id}" /> // Removing this line it works fine

</fragment>

然后,我会使用NotificationCompat.Builderwith 将 pendingIntent 用于通知:

.setContentIntent(pendingIntent) 

当我点击通知时,实际上打开了正确的目的地,但该值args.id将是“null”(不是null,而是一个具有“null”值的字符串。在我的片段中,我有

private val args by navArgs<MyFragmentArgs>()

...

override fun onCreate(saveInstanceState: Bundle?) {
   args.id // The string value is "null". 
} 

但是,如果我<deepLink>从片段中删除它,那么它将起作用。问题是我需要隐式和显式的深层链接。有没有办法同时支持导航组件?

标签: androidandroid-fragmentsandroid-architecture-navigationandroid-navigationandroid-navigation-graph

解决方案


val bundle = bundleOf("id" to "1234")

val pendingIntent = NavDeepLinkBuilder(context)
    .setGraph(R.navigation.nav_graph)
    .setDestination(R.id.myDestination)
    .setArguments(args)
    .createPendingIntent()

你的args变量是什么,因为你bundle在上面声明了?

我已经检查并且所有代码都运行良好。

我的导航图:

<fragment
        android:id="@+id/navigation_notifications"
        android:name="com.olopa.thefirst.ui.notifications.NotificationsFragment"
        android:label="@string/title_notifications"
        tools:layout="@layout/fragment_notifications">

        <deepLink app:uri="sampleapp://noti?id={id}" />

        <argument
            android:name="id"
            app:argType="string"
            app:nullable="true" />

通过通知导航时:

val bundle = bundleOf("id" to "12")

val pendingIntent = NavDeepLinkBuilder(this)
            .setGraph(R.navigation.mobile_navigation)
            .setDestination(R.id.navigation_notifications)
            .setArguments(bundle)
            .createPendingIntent()

结果: 在此处输入图像描述

或通过链接导航:

navController.navigate(Uri.parse("sampleapp://noti?id=1"))

结果: 在此处输入图像描述


推荐阅读