Close app on back button when fragment was opened by deep link of Navigation Component instead of returning to start destination fragment

Viewed 482

So for example I have two fragments:

  • start fragment which is used as start destination of my nav grapth
  • fragment for a deep link

When I open link from email it opens my app activity (recreats it if was already opened), then opens start destionation fragment and then opens deep link fragment and when I press back button it returns to start destionation fragment but I don't want such behaviour, I want it to close app instead, so fragment deep link behave as a start destination fragment

1 Answers

You can do this in several ways:

  1. If you can change your start destination, use the deeplink fragment as start destination, but I guess you have some logic in your start destination and want to navigate to the deeplink programmatically under specified conditions. In that case this solution is not applicable.

  2. by popping the backstack before navigating programmatically to the deeplink:

   // remove start destination fragment
   findNavController().popBackStack()
   findNavController().navigate(Uri.parse(<your_deeplink>))
  1. By killing the activity from the deeplink fragment. Listen for onBackPressDispatcher in the fragment, and call requireActivity().finish() from the fragment to kill the Activity. This medium post explains in the detail the onBackPressDispatcher callback.
Related