androidandroid-fragmentsfragment-backstackdeeplinknavigation-architecture

Fragment backstack building with NavDeepLinkBuilder


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.


Solution

  • 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.