Search code examples
androidandroid-fragmentsfragment-backstacktaskstackbuilder

Build fragment backStack for push notification


I am using FCM to show a fragment when user tap on the notification from the status bar.

Current app flow is this MainActivity(Fragment A -> Fragment B -> Fragment C).

However when user tap a notification (whether app is running or not), I want to show Fragment C while still providing a proper back navigation so on back key press, user is taken to Fragment B and Fragment A when pressed again.

I know activities have TaskStackBuilder for such purpose but I couldn't find anything for building backStack for fragments before showing my notification.

Any idea how I could build a stack? I tried adding all fragments into the transaction then commit before adding Fragment C but I get IllegalStateException: commit already called while on the second commit


Solution

  • Manual handling of fragment stack is hard. I would recommend you checking out Navigation Component. It will allow to build explicit deep links with proper back stack handling (NavDeepLinkBuilder class).

    Show your code. Probably you have to create new transaction for every fragment and commit operation. Use this method to add A, B and C:

        public void addFragmentOnTop(Fragment fragment) {
            getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.container, fragment)
                .addToBackStack(null)
                .commit();
        }