Before you start with Android, you need to know a thing called the Android Activity Lifecycle. This is important to know as you begin your journey as an Android dev.
In this post I’ll try to make it easier to understand
activity and how they go through various states.
The Android documentation is a bit complicated. To give you a better understanding we first need to feel comfortable with what an
activity in Android is basically every screen in which users can interact with and perform actions. Most of the time, an app will contain multiple screens (
activities) that users can use to navigate an app as they listen to music, play games, watch videos, check out pics, etc.
When developing any kind of application, it’s our responsibility to make sure our users have a great experience. And for that we need to manage our applications state responsibly.
Dive into the Technical
Here’s a diagram of Android’s
Each stage is responsible for a certain task. When you open an app or click on a button that takes you to another screen, then
onCreate() will be the first
activity cycle that gets executed. It is followed by
onResume(). And voila! We can see the interface of the app we’re creating.
activity is called,
onStop() will be also called on the first activity.
onDestroy() removes the app altogether. It is invoked when,
- You call
finish()on the current
- Your phone is short in resources (e.g., battery, memory).
What Happens at Each Stage
- This method is the first to be called when an
activityis first created. This is the place where we can create and setup views and accumulate the app’s state.
onCreate()includes a bundle, we can restore the app’s state from the data in the bundle.
- This is called immediately after onCreate(Bundle). It will make the app visible to the user.
onStart()can be called as often as needed during an
- This is the stage where your users can finally interact with your application.
- This is called when another
activitycomes into the foreground.
activitymay still be visible in the background, however we won’t be able to interact with it. An example could be when we open a dialog.
- When this gets executed you won’t be able to see your
activityor interact with it.
It’s important to note if an
activityis completely obscured by another
activity, it is stopped. It still retains all state and member information. But it is no longer visible to the user so its window is hidden.
- This is called where we reach the final stage of an
activity. There’s no going back.
At this point the system is free to garbage collect the
activitydata to free up space.
As you can see in the diagram, above, there are three key loops when maintaining
|Create the app’s state||Release all resources|
What Can We Learn From This?
It’s our responsibility as developers to make sure that we handle each of these lifecycle changes gracefully.
activityto free up valuable resources
- Make efficient use of resources
- Handle unexpected changes