Issue
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?
Solution
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")
}
}
Answered By - Sovathna Hong
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.