small medium large xlarge

20 Jun 2013, 02:19
Veronica Harbaugh (3 posts)

finish() will shut down the current activity, but is there anything that will shut down the entire application?

20 Jun 2013, 08:20
Anthony Shaw (138 posts)

The simple answer is ‘No’. A slightly more complex answer is ‘Yes, several ways, none supported by all versions of Android, and none sanctioned by Google’. Having said that, this is a common ‘problem’ where a chain of activities is started and when the last one in the chain finishes it is required that the rest of the activities finish as well. As an example lets have three activities A, B and C. A ‘does something’ (login or some such) and then starts B. B ‘does something’ (prompts for a book ISBN or some such) and then starts C. C then ‘does something’ (displays author, title, etc). The flow of control of the above is that activity A be shown only once, activity B be shown whenever activity C finishes and activity C just displays something and then quits when the user has finished with it.

This can done by using startActivityForResult(), onActivityResult() and setResult() methods.

Activity A starts activity B using startActivityForResult() and in its onActivityResult() calls finish() no matter what it gets form activity B.

Activity B starts activity C using startActivityForResult() and in its onActivityResult() can check if a shutdown option was selected in activity C by inspecting the result from C. There could also be a way of requesting a shutdown in activity B. Either way call setResult() to return something to activity A and then call finish().

Activity C is then end of the chain. When it is finished displaying its information the user will either return to activity B expecting activity B to ‘do its thing’ or, if it is implemented that way, have some way of indicating that the entire application should exit (a nice big EXIT button maybe). So, when the user want to go back to activity B activity C call setResult() and then calls finish().

In a nutshell, the way to exit an application is to call setResult() followed by finish() in each activity in turn until you get the first activity that just calls finish().