Search code examples
androidandroidxandroid-architecture-navigation

How to use navigateUp to close the application


I'm using the Android Navigation component.

Inside my HomeFragment I'm adding a OnBackPressedCallback

    OnBackPressedCallback callback = new OnBackPressedCallback(true) {
        @Override
        public void handleOnBackPressed() {
            doStuff();
            Navigation.findNavController(view).navigateUp();
        }
    };

    requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);

The problem is that navigateUp is not closing the application.

I tried to pop the stack but nothing changes.

What should I do?

Thank you


Solution

  • As per the navigateUp() documentation and popBackStack() documentation, both return a boolean value indicating:

    true if the stack was popped and the user has been navigated to another destination, false otherwise

    The NavController only controls its own back stack (i.e., the destinations you've put on the back stack) and does not contain or operate on the activity back stack.

    If you just want to always finish your activity when the back button is pressed, directly calling requireActivity().finish() is indeed the correct thing to do.

    Otherwise, you should be conditionally calling requireActivity().finish() only if popBackStack()/navigateUp() return false - that's your sign that there's nothing else on the NavController back stack and you need to handle the back stack yourself.