Sobes.tech
Junior — Middle

How to check if an activity in Android has been closed or destroyed by the system?

sobes.tech AI

Answer from AI

To check whether an Activity was closed or destroyed by the system, you can use the Activity lifecycle methods:

  • onDestroy() is called when the Activity is destroyed. If this method is called, it means the Activity is finishing.
  • isFinishing() inside onDestroy() returns true if the Activity is closing explicitly (for example, the user pressed back).
  • If isFinishing() returns false in onDestroy(), it means the Activity is being destroyed by the system (for example, due to lack of memory).

Example check in onDestroy():

override fun onDestroy() {
    super.onDestroy()
    if (isFinishing) {
        // Activity is closing by the user
    } else {
        // Activity is being destroyed by the system
    }
}

You can also track the state through onSaveInstanceState() and onRestoreInstanceState() to understand if the Activity was recreated after destruction.

How to check if an activity in Android has been… - sobes.tech