Sobes.tech
Junior

How to understand from Activity that it has been destroyed?

sobes.tech AI

Answer from AI

There are several ways:

  1. Overriding the Activity lifecycle:

    • The onDestroy() method is called before the Activity is destroyed.
    // Example in Kotlin Activity
    override fun onDestroy() {
        super.onDestroy()
        // Actions before Activity destruction can be performed here
    }
    
  2. Checking Activity state:

    • After calling onDestroy(), the Activity is in the "Destroyed" state. However, there is no direct public method to check this state from another component.
  3. Using flags:

    • You can set a boolean flag in onDestroy().
    // Example in Kotlin Activity
    private var isDestroyedByUser: Boolean = false
    
    override fun onDestroy() {
        super.onDestroy()
        isDestroyedByUser = true
    }
    
    // You can check elsewhere:
    // if (activity.isDestroyedByUser) { ... }
    
    • Important: This flag will only be valid within the same process. If the Activity is destroyed due to process termination, this method will not work.
  4. Using isFinishing():

    • The isFinishing() method returns true if the Activity is in the process of finishing (either finish() was called or the user pressed "Back"). It does not guarantee that onDestroy() has already been called, but indicates the intention to destroy the Activity.
    // Example in Kotlin Activity
    fun checkIfFinishing() {
        if (isFinishing) {
            // The Activity will soon be destroyed
        }
    }
    
  5. Observing the lifecycle with LifecycleObserver:

    • Subscribing to Activity lifecycle events using LifecycleObserver.
    // Example in Kotlin in another class
    class ActivityLifecycleObserver : LifecycleObserver {
    
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        fun onDestroy() {
            // Activity destroyed
        }
    }
    
    // In Activity (or another component with LifecycleOwner):
    // lifecycle.addObserver(ActivityLifecycleObserver())
    

The most reliable way to know about the start of the Activity destruction process is to override the onDestroy() method. For external checks, if there is no direct access to the Activity instance in its current state, it becomes more complicated and may require using flags or observing lifecycle events, considering the limitations of each approach.

How to understand from Activity that it has been… - sobes.tech