Android Activity Lifecycle
Android activity lifecycle is first thing to be known as android developer. Here I’m sharing with you some facts and code what I have learned in past 10 months as Android App developer.
What is Activity Lifecycle?
When we google for activity lifecycle most of us will get a post with block diagram of activity lifecycle. Here we are not going to explain the block diagram, If you want to know about each state refer here.
Let’s start with single activity app
As it stated in the block diagram, When we first launch the activity onCreate onStart and onResume will be states will be called.
When Activity is moved to background activity will move to Paused and Stopped state.
When activity is foreground activity is will move to Resumed state, after invoking onRestart() and onStart()
It is to be noted that onCreate is called only once for a activity, this is the reason why we are setting content view in onCreate() method. This is also same reason why we do normal static set up: create views, bind data to lists, etc in onCreate method, like assigning a view to TextView object.
What if we have multiple Activities?
When first activity is launched the activity move to Created, Started and to Resumed states.
Moving to second activity from first activity, First activity move to Stopped state only after Second activity move to Resumed state. Since First activity is moved to back stack it is not destroyed.
Moving to first activity from second activity, Second activity is destroyed only after first activity is Restarted. Second activity is destroyed since it is popped from backstack.
As you can see Started and Resumed state are called sequentially all the time. There is difference between them though.
In Started state the activity enters viewport or becomes visible. but interactions will not happen in this state.In Resumed state activity will be available for interactions.
Bonus
What if you want to do some logical checks in all the activities? Here comes Activity Lifecycle Callbacks.
Register for Activity lifecycle callbacks in Application Class to get all activities lifecycle callback at single place. Let’s say you wanted to show a toast in all activities onCreated() method. You don’t have to repeat same set of code in all the activities. Write once in onActivityCreated().
I have written about Application class and Activity LifeCycle Callbacks in detail in following article. Check it out.
Reference: https://developer.android.com/reference/android/app/Activity
Happy Learning :)
If you have any questions or comments, please feel free to drop them in the comments section below or send me a tweet.
Click the 💚 below to show your support and share it with other fellow Medium users.