Search code examples
androidandroidxandroid-architecture-navigationandroid-navigationandroid-navigation-graph

Android Navigation: removing an activity from the backStack


This question is related specifically to the androidx.navigation library.

I split up my primary graph into 2 graphs because I wanted to have one with a bottom nav with the fragments above it and one without. Instead of using <include... I added the activity to the first graph

    <activity
        android:id="@+id/Activity2"
        android:name="com...Activity2"
        android:label="Activity2" />

This all works nicely, but I also have a splash screen in the first graph that checks if the user is authenticated and navigates them directly into the second graph. With a fragment I can just use the standard popTo and popToInclusive to manage the fragment backstack but I have not been able to figure out how to do this with two activities so that when the second activity is launched the first is killed and removed from the backstack so the user cannot navigate backwards.

Currently I am just handling it in the fragment where the navigation occurs

        navController
            .navigate(R.id.action_someFragment_to_anotherFragment)
        requireActivity().finish()

and this works but it leaves room for error and I'd like to deal with it with the navigation library if possible.


Solution

  • Each individual NavController is totally independent from one another. While an <activity> destination allows you to use navigate() to go to an entirely separate activity (which may or may not use Navigation itself), Navigation itself will never finish() an activity as part of a navigate() call so you'd need to do that yourself.

    Using multiple activities with different navigation graphs is not the recommended way to handle authentication in Navigation as per the the Navigating Navigation talk and this approach fails in many ways (such as deep linking and invalidation after process death/recreation) that are correctly handled by the guide for handling login. When using one NavController and the ability to listen for navigation events, you do not run into these issues.