如何实现点击通知跳转至同一Activity内的指定Composable
实现点击通知跳转至指定Composable
1. 修改通知Intent,添加跳转标识
在你的FirNotification函数中,给Intent添加额外参数,用来标记需要跳转的目标Composable:
fun FirNotification() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notificationChannel = NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH) notificationManager.createNotificationChannel(notificationChannel) } // 创建指向MainActivity的Intent,并添加跳转标识参数 val intent = Intent(context, MainActivity::class.java).apply { putExtra("NAV_DESTINATION", "TARGET_COMPOSABLE") // 避免重复创建Activity,复用已有实例 flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP } // 适配高版本系统的PendingIntent标记,确保参数能更新 val pendingIntentFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT } else { PendingIntent.FLAG_UPDATE_CURRENT } val pendingIntent = PendingIntent.getActivity(context, 0, intent, pendingIntentFlags) notificationBuilder = NotificationCompat.Builder(context, channelID) notificationBuilder.setSmallIcon(R.drawable.ic_launcher_background) notificationBuilder.setContentIntent(pendingIntent) notificationBuilder.setContentTitle(title) notificationBuilder.setContentText(msg) notificationBuilder.setOngoing(false) notificationBuilder.setAutoCancel(true) notificationManager.notify(100, notificationBuilder.build()) }
2. 在MainActivity中处理Intent,导航到目标Composable
假设你使用Jetpack Navigation管理Composable路由,在MainActivity中处理Intent参数并完成导航:
class MainActivity : ComponentActivity() { private lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { YourAppTheme { val navController = rememberNavController() this@MainActivity.navController = navController NavHost(navController = navController, startDestination = "main_screen") { composable("main_screen") { MainScreen() } // 注册目标Composable的路由 composable("target_screen") { TargetScreen() } } } } // 处理App启动时的Intent handleNavigationIntent(intent) } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) // App在前台时,点击通知会触发此方法 setIntent(intent) handleNavigationIntent(intent) } private fun handleNavigationIntent(intent: Intent?) { intent?.getStringExtra("NAV_DESTINATION")?.let { destination -> if (destination == "TARGET_COMPOSABLE") { // 导航到目标Composable,可配置返回栈行为 navController.navigate("target_screen") { popUpTo("main_screen") { inclusive = false } } } } } }
关键细节说明
- Intent启动模式:
FLAG_ACTIVITY_SINGLE_TOP和FLAG_ACTIVITY_CLEAR_TOP确保MainActivity不会重复创建,复用当前实例。 - PendingIntent标记:
FLAG_UPDATE_CURRENT保证通知更新时,Intent的参数能同步更新;FLAG_IMMUTABLE适配Android 12+的安全规范。 - 导航覆盖场景:同时在
onCreate和onNewIntent中处理Intent,覆盖App未启动、已在前台两种点击通知的场景。
内容的提问来源于stack exchange,提问作者Daniel Gonzalez
相关产品推荐
相关产品推荐

