Sobes.tech
Junior — Middle

How to implement navigation to a specific screen in the app upon receiving a push notification?

sobes.tech AI

Answer from AI

To implement navigation to a specific screen upon receiving a push notification in Android, Intent with the necessary parameters is usually used. When a notification arrives, a PendingIntent is created in the handler (for example, in FirebaseMessagingService), which opens the desired Activity with additional data indicating which screen to display.

Example:

val intent = Intent(this, TargetActivity::class.java).apply {
    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
    putExtra("screen", "details") // passing a parameter to select the screen
}

val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

val notification = NotificationCompat.Builder(this, CHANNEL_ID)
    .setContentTitle("New notification")
    .setContentText("Tap to view details")
    .setContentIntent(pendingIntent)
    .setAutoCancel(true)
    .build()

// show notification
NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, notification)

In TargetActivity, you can read the parameter in the onCreate method and open the required fragment or screen.