androidnotificationsnavigationandroid-pendingintent

How to make notification PendingIntent target existing Activity instead of starting a new one


I'm using this answer (How to navigate to a fragment from Notification? Android Kotlin) to create a PendingIntent for navigating to a fragment when a notification is tapped (I'm actually using Java but the principle is the same):

val pendingIntent = NavDeepLinkBuilder(context)
    .setGraph(R.navigation.nav_graph)
    .setDestination(R.id.android)
    .createPendingIntent()

This is starting a new Activity and I want to target the existing one. There is a flag PendingIntent.FLAG_UPDATE_CURRENT to do this but I can't see how to use it here. Advice would be appreciated.


Solution

  • This answer shows how to set the PendingIntent flags with the NavDeepLinkBuilder by using createTaskStackBuilder: Missing mutability flags: Android 12 pending intents with NavDeepLinkBuilder

    So:

    PendingIntent pendingIntent = new NavDeepLinkBuilder(context)
                    .setGraph(R.navigation.nav_graph)
                    .setDestination(R.id.android)
                    .createTaskStackBuilder()
                    .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
    

    PendingIntent.FLAG_IMMUTABLE is required or an exception is thrown.

    Update

    I later found this didn't work, it still starts a new activity. In frustration I eventually (and for the first time) turned to asking an AI (Gemini) the question, and received an explanation of why it didn't work and a solution that does. Unfortunately SO rules on AI usage prohibit me from sharing it.