在发送通知时如何导航到特定的组合



我想知道如何在用户点击通知时将其发送到特定的组合。

我的代码是这样的,我知道它必须在Intent和PendingIntent中,但我不知道如何,我搜索,他们谈论发送到另一个Activity,但我想要相同的Activity,但不同的Composable。

fun FirNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationChannel = NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH)
notificationManager.createNotificationChannel(notificationChannel)
}
val intent = Intent(context, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)
notificationBuilder = NotificationCompat.Builder(context, channelID)
notificationBuilder.setSmallIcon(R.drawable.ic_launcher_background)
notificationBuilder.setContentIntent(pendingIntent)
//notificationBuilder.addAction(R.drawable.ic_launcher_background, "OPEN", pendingIntent)
notificationBuilder.setContentTitle(title)
notificationBuilder.setContentText(msg)
notificationBuilder.setOngoing(false)
notificationBuilder.setAutoCancel(true)
notificationManager.notify(100, notificationBuilder.build())
}

我想发送到一个不同的组合,而不是主要的。

我为此挣扎了几个小时,但找到了解决方案。所以基本上,深链接就是答案,正如这个链接[https://developer.android.com/jetpack/compose/navigation#deeplinks][1]

所述。我所做的是:

  1. 创建Pending intent与所需的deepLink,将转换为uri

    private fun createPendingIntent(deepLink: String): PendingIntent {
    val startActivityIntent = Intent(Intent.ACTION_VIEW, deepLink.toUri(), 
    this,MainActivity::class.java)
    val resultPendingIntent: PendingIntent? = TaskStackBuilder.create(this).run {
    addNextIntentWithParentStack(startActivityIntent)
    getPendingIntent(0, PendingIntent.FLAG_IMMUTABLE)
    }
    return resultPendingIntent!!
    }
    
  2. 然后在NavHost内部添加深链接参数。uri模式"https://example.com/settings"

    示例
    composable(<Composable_Route>,
    deepLinks = listOf(navDeepLink { uriPattern = <Your_URI_PATTERN> })
    ){
    val viewModel = hiltViewModel<SettingsScreenViewModel>()
    SettingsScreen(navController = navController, viewModel = viewModel)
    }
    
  3. 同样的uri必须添加到Manifest.xml作为意图过滤器。这是必需的,这样应用程序就可以知道何时使用了来自pending intent的uri。

    <intent-filter>
    <data android:scheme="https" android:host="example.com/settings" />
    </intent-filter>
    

在我的情况下,真正的https url是不需要的,所以它与类似的例子。但是,我面临另一个问题,当我从意图,返回(与android返回按钮),它会返回它需要返回的地方,但如果你试图从以前的可组合(在我的情况下,是顶部在backStackEntry)再次返回,它不会退出应用程序,但再次启动它从整个NavigationGraph的开始。如果有人有类似的问题,请与我们分享。我希望我的回答能帮助到一些人,因为Jetpack在某些方面仍然是新的,并且文档没有很好地解释。

我用putextra来解决这个问题:

val intent = Intent(context, MainActivity::class.java).putExtra("screen",screen)

,然后读取它:

val screen: String? = intent.getStringExtra("screen")
if(screen != null) {
navController.navigate(screen)
}

最新更新