There is a task for which you need to find out in onDestroy as a result of which the Activity closed, for example, by pressing the "back" button or flipping the screen.


How to find out why, at the moment, the Activity closed?

    2 answers 2

    Essentially, onDestroy() ternary state:

    1. Pressing back
    2. Screen rotation
    3. The call to finish() initiated either programmatically or by the axis itself

    Perhaps there are other reasons (colleagues will indicate if it is possible).

    Pressing back is easily tracked via onBackPressed() , screen rotation via onConfigurationChanged() . If we supplement these methods with the above proposed isFinishing() - then we can completely detect the cause of onDestroy()

    • For sure! That's what I forgot about! It was sitting in my head that there is some method that is called when the orientation is changed, but I did not remember which one. And the funny thing is that after reading your answer, I immediately came across it in Google. In the first link ... :) - Rostislav Dugin

    For this there is an isFinishing method. If this method returns true then the activation dies, i.e. clicked the back button. If false , then the screen is flipped.

    • one
      The method returns true when finish() is called to activate, and these are more options than just back. And false will be returned in many cases, not only when turning. For example, when you click the Home button, instead of Back, or open another application and many more states. This should be taken into account, everything is not as clear as in your answer (that is, the method is not a turn indicator) - pavlofff
    • It's clear))). Just do not understand what kind of case a person has. And this is an example of what you can rely on - pavel163