Retain last opened Fragment after opening push notification

20 Views Asked by At

So let's say I am in fragment_c, which is part of the navigation graph nav_home. I have a push notification that when tapped, will open fragment_e, which is in a separate navigation graph called nav_e. nav_e is included in nav_home, and only contains fragment_e.

My nav_home looks like this:

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    app:startDestination="@+id/fragment_a"
    android:id="@+id/nav_home">


    <include app:graph="@navigation/nav_e" />

    <fragment
        android:id="@+id/fragment_c"
        android:name="com.someapp.FragmentC" />

nav_e looks like this:

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/nav_e"
    app:startDestination="@id/fragment_e">

    <fragment
        android:id="@+id/fragment_e"
        android:name="com.someapp.FragmentE"
        android:label="FragmentE">
        <argument
            app:argType="string"
            app:nullable="true"
            android:defaultValue="@null"
            android:name="some_code" />

        <deepLink app:uri="someapp://somefeature/thing?someCode={some_code}" />
    </fragment>
</navigation>

When I tap the push notification, fragment_e is opened as expected, but when I tap the back button I return to fragment_a, the home destination of nav_home, whereas I am expecting to be taken back to fragment_c, the last fragment/screen opened before tapping the push notification.

In my class that extends FirebaseMessagingService I create a PendingIntent like this in onMessageReceived:

val pendingIntent = NavDeepLinkBuilder(context)
            .setComponentName(HomeActivity::class.java)
            .setGraph(R.navigation.nav_home)
            .setDestination(R.id.fragment_e)
            .createPendingIntent()

I then set the PendingIntent to a NotificationBuilder. I debugged and it seems I am opening a new instance of HomeActivity, and the previous instance is being overwritten, but how to avoid that and retain the last Fragment opened? What's the correct way to achieve what I want?

edit: The launchMode for HomeActivity is singleTask

0

There are 0 best solutions below