(Android document original translation) manage the activity lifecycle < a >

Source: Internet
Author: User
Tags home screen

(English original link address)
1. Activate your activity

Unlike other applications that start with the main () method, the Android system launches or ends an activity by invoking its lifecycle (lifecycle) callback method in a certain order. This section briefly describes the most important life cycle of activty and shows how to handle the life cycle of an activity.


Understand what is called the life cycle of callbacks

During the activity lifecycle, the Android system invokes a series of life-cycle methods similar to the pyramid arrangement in sequence, That is, each stage of the activity's life cycle belongs to a layer of the pyramid. When the system creates an activity, the invocation of each method in the life cycle allows the activity to jump (change) The state of the life cycle pyramid, and the state at the top of the pyramid is the activity's current life cycle. Visible and interoperable phases.
When the user needs to leave the activity, Other methods are called to jump the life cycle of the activity to other methods. In some cases, activity only jumps and waits partially along the pyramid (for example, when the user switches to another app).
Figure 1. A simplified illustration of the activity cycle that represents the life cycle * Pyramid of activities, which shows the changes between the activity's life cycle and the transitions between the various states of the life cycle

Depending on the complexity of your activity, you don't need to implement all the methods in your life cycle, but you need to know exactly what each life cycle means, make sure your app runs in the way your users expect it to, and to make sure your app meets the expectations of your users, but not limited to the following:
    • When a user receives a call or switches to another application, the app is not crash. When users don't use some resources, remember to release them.
    • When you leave your app and then return, your app should not lose the previous status information
    • Make sure the app is not crash and do not lose the previous status information when the application takes place in a portrait or landscape switch
In the subsequent course of study, there are several states used to represent transitions between different states in Figure 1, but only three states are static, which means that activity can survive for a long time in these three states:
Resumed in this life cycle, the activity is in the foreground, and the user can interact with it (sometimes we also call it "running" state)
Paused in this state, the activity is covered by other activity parts, others in the foreground state activity is translucent or not all covered, The overridden activity is not accepting input from the user and does not execute any code.
Stopped in this state, the activity is completely hidden and the user is not visible, the activity is considered to be in the background, when entering the stop state, All state information for this activity, such as member variables, is preserved, but no code can be executed
for other states (Creaded and stated) The life cycle of the application is quickly transformed, such as when the system calls OnCreate (), it immediately calls OnStart (), and then quickly jumps to Onresume () The above is a basic knowledge of the activity's life cycle, and we will then learn about the specific behavior of the activity.

Specify your app's startup activity When the user clicks on your app's icon in the home screen, the system invokes the OnCreate method that you declare as the "launcher activity" of the program entry, and there are several ways you can specify the entry for your app.
You can specify the app's main activity,androidmanifest.xml in Androidmanifest.xml under the root directory of your project.
This main activity must be explicitly declared in the <intent-filter> below Mainfest, including the main action in <intent-filter> and launchercategory. 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>    
Tip: When you create an Android project using the Android SDK, a default startup activity is created under the project folder

If you do not explicitly declare main action or launcher catgory, your app's icon will not appear in the list on the Home screen (the desktop of our phone).


to create a new instanceThe vast majority of apps contain multiple activity, allowing users to switch between multiple activity, a Mian activity will be created when the user clicks on the app's icon, and the system will call OnCreate () method to create an instance of an activity.
You must implement the OnCreate method to start an activity's logic and the activity's life cycle, for example, you define the user's interface in OnCreate and instantiate some variables.
For example, you explicitly declare the user interface (defined in an XML file) in the OnCreate method of the following example, define the member variables, and configure some UI configurations.

    TextView Mtextview;        Member variable for text view on the layout @Override public void onCreate (Bundle savedinstancestate) {            Super.oncreate (savedinstancestate); Set the user interface layout for this Activity//The layout file was defined in the project Res/layout/main_act                Ivity.xml file Setcontentview (r.layout.main_activity);                 Initialize member TextView So we can manipulate it later Mtextview = (TextView) Findviewbyid (r.id.text_message); Make sure we ' re running on honeycomb or higher to use ActionBar APIs if (Build.VERSION.SDK_INT & Gt;= Build.version_codes. Honeycomb) {//For the main activity, make sure the app icon in the Action Bar//does not behave a            S a button ActionBar ActionBar = Getactionbar ();        Actionbar.sethomebuttonenabled (FALSE); }    }

Once Oncreat () is executed, the system will quickly call the OnStart () and Onresume () methods, and your activity will not stay in the created and stated states when the system calls OnStart () When the method is active, the activity becomes visible, but the Onresume () method is quickly called and in the resumed state until something happens or changes, such as when the phone is called, the application is switched to the other activty, or the screen changes in a vertical row.
In the rest of the course, you'll learn that the OnStart () and Onresume () methods are useful when users return to the resumed state from the stoped and paused states.
The *note:oncreate () method contains a savedinstancestate parameter, which is a problem in the following recreating an Activity. Discussion in the course
Figure 2. Another illustration of the activity lifecycle structure with a emphasis on the three main callbacks this system call s in sequence when creating a new instance of the Activity:oncreate (), OnStart (), and Onresume (). Once This sequence of callbacks complete, the activity reaches the resumed state where users can interact with the Activit Y until they switch to a different activity.


destroying (Destroy) ActivityWhen the activity is first created, it calls the OnCreate () method, which eventually calls the OnDestroy () method, and the system will remove the instance of activity from memory when the OnDestroy () method finishes executing.
Most apps do not need to implement OnDestroy, because instance references to activity are recycled as the activity is destroyed, in OnPause () and OnStop () is cleared. However, if you have a background thread in your activity or a resource that has been referenced for a long time, you must clear the Recycle in OnDestroy (), or it will cause a memory leak.

@Override public    void OnDestroy () {        Super.ondestroy ();  Always call the superclass                //Stop method tracing that the activity started during onCreate ()        android.os.Debug. Stopmethodtracing ();    }

Note: After OnPause () and OnStop () are executed, the system calls the OnDestroy () method unless: yourself in the OnCreate () method call Finish () method. In some cases, such as when the current activity is used to temporarily initiate other activity, you may use the finish () method in OnCreate () to end the current activity, at which time the system immediately calls OnDestroy () method without being in the other life cycle.


Next:pausing and Resuming an activity


PS: The above link please bring your own VPN account, as an Android developed without VPN account a lot of information can only be used information, here I recommend the use ( red Apricot software )

(Android document original translation) manage the activity lifecycle < a >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.