简体   繁体   中英

How do you close an android app after pressing back on the phone

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.

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.

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM