Perhaps a stupid question, but how to close the Activity correctly:

before the launch of the new activation

finish(); startActivity...; 

or after

 startActivity... finish(); 
  • in general, it is not necessary to close it at all, but if there is some kind of urgent need, then after starting a new one - pavlofff
  • @pavlofff and if I need to exit the application? How else to organize the exit? For I have some bugs that I’m pressing the exit, activating again restarts, although onBack .. it is written finish (), after the second click, everything closes - shcherbuk

1 answer 1

Actually, it makes no difference. All the same, these methods are not direct (immediate), but will be executed in reality only after they fall into the MessageQueue message processing queue , which is executed in the UI Thread - in the so-called MainLooper ( Looper.getMainLooper() )

In fact, the call to finish() and startActivity() , as well as any actions with the window system a la setText() will be translated into messages that Looper will process - approximately as in the picture:

enter image description here

From this point of view, the sequence does not matter.

  • Doesn't the line mean that the actions will be executed in the order in which they got into it (they were called in the code)? - eugeneek
  • one
    Quite right, the queue implies that they will be executed exactly this way, but this does not mean that at the moment of execution startActivity() Activity will be destroyed, before which finish() was called. That is, if the methods were direct actions, then such behavior would lead to a collapse, roughly speaking, it would not have been possible to first destroy, and then cause something from the destroyed instance ... Something like this. - Barmaley