从 navDeepLinkBuilder.setArguments(bundle) 访问 Bundle

Access the Bundle from navDeepLinkBuilder.setArguments(bundle)

有一个服务会在某个时候创建​​一个始终指向相同片段的通知。 Service 想要向 Fragment 发送一些键值数据。在 Intent 中,我会将这些作为 Extras。 PendingIntent 没有 putExtras 方法,但 NavDeepLinkBuilder 有一个采用 Bundle 的 setArguments 方法。

val pendingIntent = NavDeepLinkBuilder(applicationContext)
            .setComponentName(MainActivity::class.java)
            .setGraph(R.navigation.nav_main)
            .setArguments(myExtras)
            .setDestination(R.id.destinationFragment)
            .createPendingIntent()

val builder = NotificationCompat.Builder(this, CHANNEL_ID)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setContentText("some text")
            .setContentTitle("some text")
            .setContentIntent(pendingIntent)

startForeground(NOTIFICATION, builder.build())

稍后可以从目标 Fragment 访问输入到 setArguments 的包吗?我按以下方式尝试了它,但它只是 returns 我的默认值:

activity?.intent?.extras?.let {
    val myExtra = extras.getInt(KEY, DEFAULT_VALUE)
    Timber.e("got the Value $myExtra")
}

是的,您可以从目标片段访问您的包。看看这个

//your fragment
override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    super.onCreateView(inflater, container, savedInstanceState)

    if (arguments != null) {
        if (requireArguments().containsKey(YOUR_KEY)) {
            //logic
        }
    }
}