0

On my app I would like to close the app when reaching the mainActivity. At the moment I have noHistory added to all activities in the manifest because I am overriding the navigation based on how I would like the app to flow.

What code would I put into the onBackPressed function to close the app?

The issue I have is that I do not want to use noHistory because when moving between apps or minimizing the app, the app will load from the splash screen again when you open it which is not helpful for navigation

NOTE: I have a splash screen implemented as well.

Waseem Ahmed
  • 379
  • 1
  • 5
  • 17

3 Answers3

1

The root activity can use startActivityForResult with a certain request code constant. The next activity can call setResult(RESULT_OK, Intent()) in its onCreate (not sure if this step is necessary). Then back in the first activity, override onActivityResult and call finish() if the request code matches the one you used in the startActivityForResult call.

No need to override onBackPressed.

Alternatively, the root activity can simply call finish() immediately after startActivity(). Then it won’t be in the back stack at all.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154
1

You can just call finish() in onBackPressed(). It should be enough. Alternatively you can call System.exit(0).

More here: Difference between finish() and System.exit(0)

Demigod
  • 5,073
  • 3
  • 31
  • 49
  • i have tried the finish() option, but it still loads the previous activities, do i need to add that onto every single activity? bear in mind, i do not want to use noHistory because over the multitasking taking me back to the splash screen if i do. If i add finish() to each activity then does this stop firestore snapshots from running, because i have notifications linked to snapshopts. – Waseem Ahmed Jan 22 '20 at 14:00
  • @WaseemAhmed, usually, `finish()` is called in the `SplashActivity`, when you're launching "main" activity after `SplashActivity`. And also call `finish()` in `onBackPressed()` of your "main"/"root" activity. (To shutdown whole app use `System.exit(0)` – Demigod Jan 22 '20 at 15:47
0

The answer is kind of combination of all but much simpler but a little cumbersome.

What i actually needed to do was add finish() wherever i had a startActivity in each of the activities and this could have been multiple depending on the actions in the page.

This ultimately allows navigation back tot he main page and when closed, "minimizes" the app in the app drawer of the phone.

Waseem Ahmed
  • 379
  • 1
  • 5
  • 17