Monday, July 4, 2011

Android Kill Self-process

I came across a line of source code written by some others today, and it gives me a behavior I have never thought about. The whole application (simplified version) consists of two activities. A user first launches up the main activity and clicks a button in this activity. This starts the second activity. The user then clicks a button in the second activity, and this line is called:

I thought the whole application will be killed and the system will go back to home screen but it does not. Instead the application goes back to main activity and calls its onCreate() again. I am surprised, and then I did a test. I added finish() in main activity after startActivity(). This time, killing the process just closed the whole application.

I tried to search for the reason of this behavior but I cannot find out the answer. Normally, processes are managed by Android system and one should not handle them himself. I believe this behavior is because some resource is not freed yet when the process is killed, and the system thinks the application should relaunch (or it thinks the application is still launching for the first time?).