Fragment backstack building with NavDeepLinkBuilder
Asked Answered
L

2

7

I have a single activity app, with three fragments, A, B, C. In the normal app flow, fragments are opened in sequence: A->B->C I have a foreground service with a notification that when clicked, should open fragment C. I use Navigation Architecture Component, and add the destination to the notification as a deeplink:

NotificationCompat.Builder(context, NOTIFICATION_CHANNEL)
    ....
    .setContentIntent(NavDeepLinkBuilder(context)
        .setGraph(R.navigation.main_navigation)
        .setDestination(R.id.fragmentC)
        .setArguments(bundle)
        .createPendingIntent())
    .build()

The fragment backstack is not built. When I navigate back from fragment C, I immediately get to fragment A, not to B. According to Principles of navigation the backstack shall be natural, but I cannot seem to be able to achieve that. What am I missing here? Thank you.

Lettering answered 27/5, 2020 at 13:44 Comment(1)
This is default behavior of NavGraphLectra
L
4

I achieved the desired backstack by refactoring my navgraph to nested graphs. As it is shortly mentioned in NavDeepLinkBuilder reference "The destination and all of its parents will be on the back stack.", and "The parent of the destination is the start destination of the containing navigation graph".

Together these two means that the backstack will consist of the start destinations of all the nested navigation graphs the deeplink destination is part of.

Initially I had a single nav graph, with no nesting, and my only backstack item was the start destination of that graph. When I refactored the navgraph to consist of a main (outer) nav graph and a nested graph, the backstack consisted of the start destination of both graphs.

Lettering answered 28/5, 2020 at 7:43 Comment(0)
R
-1

To achieve that, you need to start your root element (activity or fragment, which started the stack) and it will automatically restore everything to the last added fragment, but make sure that fragments are added to the backstack.

In case you will need to restore to another fragment, you can listen to this intent and just reset to the required transaction.

Rolo answered 27/5, 2020 at 14:21 Comment(4)
How you start the root element (activity or fragment), with NavDeepLinkBuilder?Misshape
@Shefchenko, developer.android.com/reference/kotlin/androidx/navigation/…Rolo
your link is for popBackStack(), but that's not starting any root element (activity or fragment).Misshape
@Shefchenko, it has flag pop inclusiveRolo

© 2022 - 2024 — McMap. All rights reserved.