What is this Activity Lifecycle?
Android apps do not have a “main” method so you gotta figure out how to start and stop them. The class Activity provides a number of well-defined life-cycle methods that are called when an application is started, suspended, restarted, and so on, as well as a method you can call to mark an activity as finished.
In the above figure, if you notice carefully, when you start your app, these 3 methods are called one after the other in perfect order.
Your Android application runs in its own Unix process, so in general it cannot directly affect any other running application. The Dalvik VM interfaces with the operating system to call you when your application starts, when the user switches to another application, and so on.
An Android application has three states it can be in:
- Active, in which the app is visible to the user and is running
- Paused, in which the app is partly obscured and has lost the input focus
- Stopped, in which the app is completely hidden from view
For an application’s first activity, onCreate() is how you know that the application has been started. This is where you normally do constructor-like work such as setting up the “main window” with setContentView(), adding listeners to buttons to do work (including starting additional activities), and so on.
In the above figure, when you move to a different application from your app, onPause() and onStop() are called
From the other app that you launched, if you come back to your app with the BACK button, then the above 3 methods are called in perfect order.
Ultimately, when your app exits permanently or you press the BACK button inside your app, onDestroy() gets called which indicates that your app is exiting. If the number or order of the methods seem confusing, here is an overall figure that includes the whole lifecycle at once. We just wanted to reveal this step-by-step
When you start your app, onCreate(), onStart(), onResume() gets called where onCreate() can be used like a constructor. When you move to some other app and your screen is partially blocked, onPause() is called, if your screen is fully obscured, onStop() is called. When you come back to your app from another app, onRestart(), onStart(), onResume() is called. When you press back button inside your app, onDestroy() gets called and your Activity is destroyed. Use the Activity lifecycle wisely and you’ll making amazing apps.