When a user navigates, exits, and returns to your app, the Activity instances in the app will transform different states in their life cycle. For example, when your activity first starts, it will appear in the system foreground and receive the user focus. In this process, the Android system invokes a series of life-cycle methods on the activity, through which you can set up the user interface and other components. If a user performs an action that starts another activity or switches to another app, when it enters the background (where activity is no longer visible, but the instance and its state are intact), the system invokes a different set of life-cycle methods on your activity.
Within the life cycle callback method, you can declare the activity behavior of the user when they leave and re-enter the activity. For example, if you are building a streaming video player, you may want to pause the video or terminate the network connection when the user switches to another app. When the user returns, you can reconnect to the network and allow the user to continue playing the video from the same location.
This lesson describes the important lifecycle callback methods that each activity instance receives and how you can use them to make your activity work as expected by the user and not consume system resources when your activity does not need them.
Start and destroy activity
Unlike main() other programming paradigms that use methods to launch applications, the Android system launches code in the Activity instance by invoking a specific callback method corresponding to a specific stage in its life cycle. There is a series of callback methods that initiate activity, and a series of callback methods that decompose the activity.
This course outlines the most important life-cycle approaches and shows you how to handle the first lifecycle callback that creates a new instance of activity.
Understanding Life cycle Callbacks
During the activity's life cycle, the system invokes a set of core life cycle methods in a sequence similar to a ladder pyramid. In other words, each stage of the activity's life cycle is the first order of the pyramid. When the system creates a new activity instance, each callback method moves the activity state to the top of the first order. The top of the pyramid is the point in time that the activity runs in the foreground and the user can interact with it.
When the user starts to leave the activity, the system calls other methods to move the activity state down in the pyramid, destroying the activity. In some cases, activity will move down and wait only partially in the pyramid (for example, when the user switches to another app), the activity can move from that point back to the top (if the user returns to the activity) and continue where the user stopped.
Figure 1. Simplified activity life cycle diagram, expressed as a ladder pyramid. This illustration shows that for each callback that is used to move the activity to the top of the "continue" state, there is a callback method that moves the activity down one step. The activity can also return to the resume state from the pause and stop states. *
Depending on the complexity of your activity, you may not need to implement all life cycle methods. However, it is important to understand each method and implement a method that ensures that your app runs in the way the user expects it to. Correctly implementing your Activity lifecycle approach ensures that your app works well in several ways, including:
- If a user listens to an incoming call or switches to another app while using your app, it doesn't crash.
- Valuable system resources are not consumed when the user is not actively using it.
- If a user leaves your app and returns later, the user's progress will not be lost.
- When the screen rotates between landscape and portrait, it does not crash or lose the user's progress.
As you will learn in the following courses, there are several situations where activity transitions between different states as shown in Figure 1. However, only three of these states can be static. In other words, activity can only exist for a long time in three states.
- resumed: In this state, the activity is in the foreground and the user can interact with it. (sometimes also called a "run" state.) )
- Paused: In this state, activity is blocked in a semi-transparent state in the foreground or another activity-that does not cover the entire screen. Paused activity does not receive user input and cannot execute any code.
- Stopped: In this state, the activity is completely hidden and invisible to the user; It is considered to be in the background. When stopped, the activity instance and all state information, such as member variables, are preserved, but it cannot execute any code.
Other states ("Create" and "start") are transient,
Other states (Created and Started) are transient transients, and the system quickly moves from these states to the next state by invoking the next life cycle callback method. That is, after the system calls OnCreate ()), it quickly calls OnStart ()), followed by a quick call to Onresume ()).
The Basic life cycle section ends here. You will now begin to learn some knowledge of specific life cycle behavior.
Specifies the activity that the program starts for the first time
When the user taps the program icon from the main interface, the system invokes the OnCreate () method in the app that is declared "launcher" (or "main") activity. This activity is used as the main entry point for the program.
We can define activity as the main activity in Androidmanifest.xml.
This main activity must be used in manifest including main action and LAUNCHER category <intent-filter> tag to declare. For example:
<activity android:name=. Mainactivity "android:label=" @string/app_name "> <intent-filter> < action android:name= " Android.intent.action.MAIN "/> <category android:name=" Android.intent.category.LAUNCHER "/> </intent-filter></ACTIVITY>
Note: When you use the Android SDK tool to create an Android project, the project contains a default activity class that declares the filter.
If the activity of main action or launcher category is not declared in the program, the app icon will not appear in the device's main interface list.
To create a new instance
Most apps include multiple activities, allowing users to perform different actions. Whether this activity is the main activtiy created by the user clicking on the app icon or other activity created in response to user behavior, the system invokes the OnCreate () method in the new activity instance.
We must implement the OnCreate () method to perform the basic logic needed to start the program. For example, you can define the UI and instantiate class member variables in the OnCreate () method.
For example, the following OnCreate () method demonstrates some of the underlying operations required to create an activity. such as declaring UI elements, defining member variables, configuring the UI, and so on. (OnCreate inside as little as possible to do things, to avoid the program start too long can not see the interface)
TextView Mtextview;//Member variable for text view in the layout@Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); //Set The user interface layout for this Activity//The layout file is defined in the project Res/layout/main_activity.xml fileSetcontentview (r.layout.main_activity); //Initialize member TextView So we can manipulate it laterMtextview =(TextView) Findviewbyid (r.id.text_message); //Make sure we ' re running on honeycomb or higher to use ActionBar APIs if(Build.VERSION.SDK_INT >=Build.version_codes. Honeycomb) {//for the main activity, make sure the app icon in the action bar//does not behave as a buttonActionBar ActionBar =Getactionbar (); Actionbar.sethomebuttonenabled (false); }}
Caution: Use Sdk_int to avoid the old system calling methods that are available only on Android 2.0 (API level 5) or newer systems (the code in the If condition above). These methods are called by the old system to throw a run-time exception.
Once the oncreate operation is complete, the system quickly calls the OnStart () and Onresume () methods. Our activity will not stay in the created or started state. Technically, the activity begins to be visible to the user after OnStart () is called, but Onresume () is executed quickly so that the activity stays in the resumed state until some factors change to change the state. For example, a call is received, the user switches to another activity, or the device screen shuts down.
In a later lesson, we'll see how other methods are used, and OnStart () and onresume () are useful when a user recovers from a paused or stopped state.
Note: the OnCreate () method contains a parameter called Savedinstancestate, which will be involved in the subsequent course-re-creation of the activity.
Figure 2. Shows how OnCreate (), OnStart (), and Onresume () are executed. When these three sequential callback functions are completed, the activity reaches the resumed state.
Destroying activity
The activity's first life-cycle callback function is OnCreate (), and its last callback is OnDestroy (). This method is called when a signal needs to be completely removed from the activity.
Most apps do not need to implement this method because the references of the local class will be destroyed as the activity is destroyed, and our activity should execute the cleanup activity resource in OnPause () and OnStop (). However, if the activity contains a background thread created at the time of the OnCreate call, or other resource that could potentially cause a memory leak, the resource cleanup should be done at OnDestroy () to kill the background thread.
@Override Public void OnDestroy () { Super. OnDestroy (); // Always call the superclass // Stop method Tracing that the activity started during onCreate () android.os.Debug.stopMethodTracing ();}
Note: unless the program calls the finish () method inside the OnCreate () method, the system usually executes OnPause () and OnStop () before calling OnDestroy (). In some cases, for example, our activity just does a temporary logic jump function, it is only used to decide which activity to jump to, so we need to call the finish method in OnCreate, so the system will call Ondestory directly, Skipping other methods in the life cycle.
6) 10 minutes to learn the start and destruction of the life cycle of android--activity