4

I have an activity A with several execution branches that end with a call to finish(). Reading the documentation, my understanding is that this will result in onDestroy() being called at some point for activity A if and when finish() is called. Later on, activity A might be restarted by activity B.

However, I am observing that this isn't always what happens. In rare cases onDestroy() is not called before activity A is restarted by activity B following activity A calling finish(). This is especially true if activity B restarts activity A very soon after activity A calls finish(). This possibility matches with the lifecycle graph (see here).

My question is as follows. Suppose that Activity A is in the running state and calls finish(). Can any guarantee be made about activity A calling onPause() or onStop() before activity B restarts activity A (irrespective of how soon/late in the future the restart occurs)? Moreover, once Activity A restarts, is there any guarantee that onCreate(), onStart(), or onResume() will be called? Put another way, my question is if an activity is in the running state and finish() is called what are the possible paths through the lifecycle graph that activity may take to return to the running state?

0

3 Answers 3

1
+50

Activity A onPause(), and onStop() is guarantee to be called when you call to finish(). But onDestroy() is not guarantee to be called when activity A restarts activity B. When activity A is restarting onCreate(), onStart(), and onResume() will be called respectively.

But all the lifecycle events is guarantee to be called when you use the activity Lifecycle to observe the Lifecycle.Event of say activity.

You can test it like below to see for yourself:

class ActivityB : AppCompatActivity() {
    override fun onResume() {
        super.onResume()
        startActivity(Intent(this, ActivityA::class.java))
    }
}
    
class ActivityA : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        Log.d("tag","onCreate")

        lifecycle.addObserver(object:LifecycleEventObserver{
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                Log.d("lifecycleEvent","$event")
            }
        })
    }
    override fun onStart() {
        super.onStart()
        Log.d("tag","onStart")
    }

    override fun onResume() {
        super.onResume()
        Log.d("tag","onResume")
    }

    override fun onPause() {
        super.onPause()
        Log.d("tag","onPause")
    }

    override fun onStop() {
        super.onStop()
        Log.d("tag","onStop")
    }
}
0

finish() What happens?

The method that called finish() will run to completion. The finish() operation will not even begin until you return control to Android. so, every life cycle event like onCreate, onResume, onPause, onDestroy of an Activity is always called on a single thread - The Main thread.

In short, this thread is backed by a Queue into which all the activity events are getting posted. This thread can execute all these events in the order of insertion.

If you are calling finish() in one of the life cycle callbacks like onCreate() a finish message will get added to this queue but the thread is not free to pick & execute the finish action until currently executing method returns i.e Thread is freed from current task.

The ondestroy() is the final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.

If there are two activities A and B. And your flow is going from A -> B and B=A calls finish(), Then, the method where you called finish() from will execute as Mark mentioned. And the flow of callbacks will be as followed -

onPause() of activity A
onRestart() > onStart() > onResume() of Activity B

Then, comes the real difference. If you did not call finish() from activity A; only onStop() of ctivity A will be called here. While, in this case, where we called finish() from Activity A; So onStop() and onDestroy() both will be called for activity A.

-1

tldr; Calling finish() will guarantee that onDestroy() is called so you can gracefully clean up objects in memory. This also means we will always expect the lifecycle to start from the beginning if and when the same activity is called to the foreground again.

If onRestart() is called, that means the activity was not destroyed and thus means onDestroy() was not called either. finish() is used to destroy an activity, so that means finish() was never called either.

If finish() is called, the only certainty is that onDestroy() will be called. I believe the other lifecycle methods can be called, but depends on when (current state of the activity) finish() is called.

If onDestroy() is called, a new instance of the activity will be created, which means it will start from onCreate().

You can add log outputs for each lifecycle method and try calling finish() from each of them and see what occurs. If the behavior is consistent, you can try to ensure that your logic is being triggered at a certain lifecycle event if you want/need to add reactive code to lifecycle events.

Note: We call finish() when we explicitly want to destroy the activity from memory.


Update:

"If finish() is called, the only certainty is that onDestroy() will be called"

is the defined behavior from the android docs and it's what we should expect. If and when you observer behavior that is different from what is expected, then it's a potential sign that the code is likely functioning improperly. In the scope of your question, the problem would either be originating from the android environment, or from your code (more specifically, how you manage Activity navigation within the project).

I would first check with the official android issues tracker and see if there are any existing reports that are similar to what you experience. And then I recommend you review how your app is handling navigation between activities.

From what I know, the purpose of finish() is to allow us to destroy an activity at-will (and its destruction should be observably instantaneous). So if you are somehow exiting Activity A to enter Activity B, and then exiting Activity B to re-enter Activity A, this flow must be happening considerably fast. Not sure how fast we're talking about here, but assuming that this is how your app is supposed to behave, then you probably don't need to call finish(), because you'll want to preserve the activity in the backstack. If this is not how your app is supposed to behave then you're either creating some weird race condition, or the app is actually creating another instance of the same Activity - reviewing the link on the backstack explains about Activity Tasks.

As a reminder, these are merely suggestions because I have no idea how your app is supposed to work, what it does, and how the code is implemented.

2
  • "If finish() is called, the only certainty is that onDestroy() will be called" is not true. Not only does it not match the android lifecycle graph, I have observed it happening (onDestroy not being called). Specifically, if finish is called and the activity is started via "startActivity(intent)" very, very soon after finish is called onDestroy will not be called. In fact, it was the observation (that onDestroy is not always called) that led to me asking this question.
    – HXSP1947
    Apr 27, 2022 at 19:16
  • Excuse me I should have been more clear. I will make an edit to my previous answer to address your comment.
    – zuko
    Apr 27, 2022 at 23:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.