Search code examples
androidandroid-intentandroid-serviceandroid-notificationsandroid-pendingintent

Receiving explicit intents while activity is in the foreground


My app has one activity and one service. The service starts a foreground notification that has an action button that in some situations needs to tell the activity to do something besides just coming back to the front. It uses the Extras to indicate this something.

My issues are that I can't find any documentation on how to receive explicit intents other than through the "bundle" passed to onCreate() which isn't usually called because the activity could already be created.

How do you receive an intent after onCreate()?

Notification code snippet:

    val actionIntent = Intent(this, MainActivity::class.java)
    actionIntent.action = actionText
    actionIntent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
    val pendingActionIntent: PendingIntent = PendingIntent.getActivity(this, 0, actionIntent, 0)
    
    val actionCancel: NotificationCompat.Action = NotificationCompat.Action.Builder(R.drawable.ic_cancel_black_24dp,
                                                                                    actionText,
                                                                                    pendingActionIntent).build()
    
    val notificationBuilder: NotificationCompat.Builder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
            .setContentTitle(getText(R.string.notification_title))
            .setSmallIcon(R.drawable.ic_logo_24dp)
            .setContentIntent(pendingIntent)
            .setOnlyAlertOnce(true)
            .addAction(actionCancel)
            .setContentText(text)
    
    startForeground(ONGOING_NOTIFICATION_ID, notificationBuilder.build())

Solution

  • Override onNewIntent(). If the activity already exists, and an Intent is bringing it back to the foreground, that Intent is delivered to onNewIntent().