How to use Android Activity's finish(), onDestory() and System.exit(0) methods

时间:2024-06-30 21:37:20

Activity.finish()

Calling this method will let the system know that the programmer wants the current Activity to be finished. And hence, it calls up onDestroy() after that.

The system will remove the top level activity from stack when calling finish(). However the system will not call onDestory() immediately so that means allocated resources aren’t free at the moment. Since the activity is removed form the stack, you won’t be able to go back the activity when you press the ‘back’ button. Actually onDestroy() is not just triggered by finish(), the system can call it on it’s own as well.


Activity.onDestory()

The final cleanup method, destroying this instance and freeing up resources.

The last state in the Activity Life-cycle. All resources will be gone. You should free up resources that you can on your own, e.g. closing open connections, readers, writers, etc. But if you don’t override it, the system does what it has to. When you want to re-enter this activity, it must be re-created and executing onCreate() method


System.exit(0)

This method will exit the application. It will kill the process of this application.


One last thing

In one of my own project, I call the finish() method based on the requirement.
My project has only 3 pages and the transitions as follow:

Main Page <--> Login Page <--> Signup Page

There is a back button in the Signup Page, it is to back to last activity to login. When I was first testing on the button, it didn’t work as I expected as

Main Page <-- Login Page <-- Signup Page

It worked as: Login Page <–> Signup Page and after a few cycles, it then back to the Main Page。
As new activity was always been created, and pushed on the stack. It will be pulled one by one, so it will shows like that.

The transition is been performed by calling startActivity(new Intent(…..)). After some studies, the finish() method should be called based on the situation.