Activity's life cycle function

Source: Internet
Author: User

Objective:

The previous article wrote about the activity life cycle and life cycle State, an article to talk about activity life cycle functions.

Main activity:

The application's portal is usually the desktop app icon, and the user clicks the app icon to open the app, because the app has the main activity, and without the main activity, the application doesn't appear on the desktop. The main activity is declared in Androidmanifest.xml as follows:

XHTML
123456 <activity android:name=". Mainactivity " android:label=" @string/app_name "> <intent-filter> <action android:name="Android.intent.action.MAIN" /> /c1> <category android:name="Android.intent.category.LAUNCHER" /> </intent-filter> </activity>

The difference between the Androidmanifest.xml statement and the normal activity is that there is more <action android:name= "Android.intent.action.MAIN"/> and <category Android:name= "Android.intent.category.LAUNCHER"/>. The activity has these two claims to be found in the list of desktop applications.

The life cycle method of the activity will be recalled by the system, what is the timing of their invocation? What do you need to do in these methods? Take a look at a picture and explain what you might understand in contrast to the diagram.

Images from Google's developer official website.

Oncreat Method:

The Oncreat method is only called once during the activity life cycle, and the activity enters the created state after oncreat. The main task in this approach is to initialize the resources you need for this activity and load the UI. Initialization resources are typically variables that you define. Loading the UI is typically done by first setting up the layout in the XML file and then loading it through Setcontentview (layout_xml) onto the application window (which can be understood as a window at the outermost of every application's interface, called window, All the view is displayed on this window). The instance code is as follows:

1234567891011121314 TextView mtextview; //Member variable for text view in the layout@Overridepublic void onCreate(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 file setcontentview(R. Layout. Main_activity);      //Initialize member TextView So we can manipulate it later mtextview = (TextView) Findviewbyid(R. ID. Text_message); }

OnStart Method:

The Oncreat method executes immediately after the call to the OnStart method, OnStart the method after the activity enters the started state. Generally this method is not necessary, because there are other ways to replace it to do the work that needs to be done. When this method finishes calling, the view becomes visible, but it is not interactive. From the beginning, you can see that the OnStart method may be called multiple times throughout the life cycle, and once the activity enters the stoped state, it may again go through onrestart-OnStart method again into started state.

Onresume Method:

After the OnStart method executes, the Onresume method is called immediately after which the activity enters the resumed state, where the activity gets the focus and can be seen interactively, which may be called multiple times in the life cycle. As long as the entry into the interactive state is bound to go this way. When entering this method you need to be ready to interact with the resources of the user, that is, users want to see the user to click on the UI resources to be able to quickly respond to the user, such as to prepare a music player, the user click Play immediately can hear music.

OnPause Method:

When the activity is partially or completely obscured by the foreground UI, the activity loses focus and is not interactive onpause. such as pop-up dialogs, or go to other activity interfaces. In this method you have to deal with the resources that the user no longer needs, such as Stop the game, stop the player, and need to save the user's current data, such as game data (level progress), play data (playback progress), etc., but do not take too much time to operate. The recommendations on Google's website are:

    • Stop animations or other ongoing the actions that could consume CPU. (Stop everything that consumes CPU, animations, threads, etc.)
    • Commit unsaved changes, but only if the users expect such changes to being permanently saved when they leave (such as a draft EMA IL). (Automatically saves data that the user does not submit, such as an edited message draft.) )
    • Release system resources, such as broadcast receivers, handles to sensors (like GPS), or any resources the may affect bat Tery life While your activity was paused and the user does not need them. (When activity is paused, frees up system resources that users no longer need, such as: Broadcast, GPS, or Other power-consuming devices. )

Examples of official websites are as follows:

1234567891011 @Overridepublic void onPause() { Super.   OnPause(); // Always call the superclass method first //Release The Camera because we don ' t need it when paused //and other activities might need to use it. if (mcamera! = null) { Mcamera. Release() mcamera = null;     }}

OnStop Method:

When the activity's OnStop method is called, the activity goes into the stoped state, completely invisible, and you need to completely release the resources that the user no longer needs, although you have previously called the OnPause method to release a subset of the resources, However, in the OnPause method you cannot execute a larger, more CPU-intensive method, which is allowed in OnStop. For example, to save data to a database:

1234567891011121314151617 @Overrideprotected void onStop() { Super.   OnStop(); // Always call the superclass method first //Save The note ' s draft, because the activity is stopping //And we want to is sure the current note progress isn ' t lost.     contentvalues Values = new contentvalues (     values.put (notepad.notes. Column_name_note, getCurrentNoteText values. Put(NotePad. Notes. Column_name_title, getcurrentnotetitle()); getcontentresolver(). Update( MUri, //The URI for the note to update. values, //The map of column names and new values to apply to them. null, //No SELECT criteria is used. null //No WHERE columns is used.             );}

In the stoped state, when the system resources are strained, the activity will be reclaimed directly by the system and no longer call the OnDestroy method, which is very extreme.

OnDestroy Method:

The last method of the activity life cycle, which generally does not do anything in this way, should be called for it. Most of the cleanup work is done in the OnPause and OnStop methods, which is the last chance to finish the cleanup, and some threads that might cause a memory leak should stop in this method, and the hander message will be cleaned out.

Summarize:

I used two articles to talk about the life cycle and life cycle methods of the activity, mainly to understand what to do in each life cycle approach, not to do those things, so that the UI is displayed correctly and quickly, the data is saved, and the freed resources are freed. If you have any questions you can pay attention to the following public number to my message, we discuss together.

focus on the public platform: the Programmer Interaction Alliance (coder_online), You can the first time to get original technical articles, and (Java/c/c++/android/windows/linux) technology Daniel to be friends, online communication programming experience, Get the basics of programming, solve programming problems. Programmer Interactive Alliance, Developer's own home.

Activity's life cycle function

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.