Android Growth Path (3)--activity life cycle (1)

Source: Internet
Author: User

When the user is using an app, the activity is converted in a different life cycle state.

When the user leaves or goes back to an activity, we can write some related actions in the life cycle callback function. For example, if a user opens a video player and when he switches directly to another app, the player should pause and disconnect the network that gets the video resource. When the user comes back, we want to reconnect to the network to get the video resource and let the user start the re-viewing in the position just paused.

Next, start to understand the very important life cycle callback functions, learn how to use them to perform some of the things that users have a better experience with, and don't consume the resources of the system when we don't need them. In Android, instead of starting a main () method like any other program, you start an activity instance by invoking a callback function that corresponds to a specific state of the lifecycle.

Start an activity

In the life cycle of an activity, the callback function can be viewed as a ladder pyramid. That is, the stage of each activity life cycle is a step on the pyramid. When the system starts to start an activity, the callback function allows the activity to ascend one step to the top of the stairs. At the highest level, the runtime activity can be fully displayed, interacting with the user.

When the user exits the current activity, the system calls other methods, allowing the activity to go down the highest level of the stairs and it will not be in the foreground. Sometimes it just goes down the pyramid and waits there (for example, the user switches to another app). This time the activity can go up to the top of the pyramid (the user is back to the previous activity), the user continues to leave the place to operate.

It may not be necessary to implement all life cycle functions in real development, but it is important to understand the implementation of each function to ensure that the app executes the way the user expects it.
Here are a few things to keep in mind:
1, when the user has a call or switch to other apps, do not destroy the current app
2, when the user does not use the system resources, to turn off, do not consume system resources
3, when the user left the app after a while to the app, do not lose the user's progress
4. When the screen rotates between landscape and portrait, do not lose the user's progress.

When the activity is converted at different stages, such as.
However, only three stages are static. Activity will only stay for a long time at one of these three stages:

resumed
At this stage, the activity is displayed in the foreground, interacting with the user. That is, the running phase.
Paused
At this stage, the activity is partially obscured by other activity, and the activity cannot receive the user's input or execute any code.
Stopped
When activity is in the stopped phase, it is completely masked and the user is not visible. This is the activity instance and some of his member variables remain, but it will not execute any code.

At other stages (Created and Started) are instantaneous, the system invokes the function of the next life cycle and quickly jumps to the next stage. So after the system calls OnCreate (), it will soon call OnStart () and then immediately follow Onresume ().

Specify the app's startup activity

In Androidmanifest.xml, you can specify which activity to use as the main activity. This main activity is declared in < Intent-filter >, including the main action and LAUNCHER category.
For example:

<activity  android:name  = ". Mainactivity " android:label  =" @string/app_ Name ";  <intent-filter ;  
    
     <
     action  
     android:name  =< Span class= "Hljs-value" > "Android.intent.action.MAIN" />  
     <category  android:name  =" Android.intent.category.LAUNCHER "/>  
     </ Intent-filter ;  
     </activity ;  
    
OnCreate

Most apps will have several different activity, and when the user clicks to open the app, the system will create each new activity by calling the OnCreate () method.
The OnCreate () method must be implemented to perform some of the activity's UI, data loading, and so on, which is performed only once throughout the life cycle. For example, define a user interface port in XML, define member variables, and configure some UI.

The code in the last displayactivity:

protected void OnCreate (Bundle savedinstancestate) {Super. OnCreate(savedinstancestate);Setcontentview (R. Layout. Activity_display_message);Toolbar Toolbar = (Toolbar) Findviewbyid (R. ID. Toolbar);Setsupportactionbar (Toolbar);Floatingactionbutton fab = (Floatingactionbutton) Findviewbyid (R. ID. Fab);Ha. Setonclicklistener(New View. Onclicklistener() {@Override public void OnClick (view view) {Snackbar. make(View,"Replace with your own action", Snackbar. LENGTH_long). Setaction("Action", null). Show();}        });Getsupportactionbar (). setdisplayhomeasupenabled(true);Intent Intent = Getintent ();String message = Intent. Getstringextra(mainactivity. EXTRA_message);TextView TextView = new TextView (this);TextView. Settextsize( +);TextView. SetText(message);Relativelayout layout = (relativelayout) Findviewbyid (R. ID. Content);Layout. AddView(TextView);}

Once OnCreate () executes, the system calls the OnStart () and Onresume () methods immediately thereafter. Activity does not stay in the two stages of created and started. In fact When the OnStart () method is called, the user can already see the activity, except that Onresume () is immediately invoked, and the activity enters the resumed state until the user switches to another app or has a call, or closes the screen.

When creating a new activity instance, focus on these three callback methods: OnCreate (), OnStart (), and Onresume (). Once the callback method executes, the activity goes to the resumed stage, where the activity returns to the foreground and the user interacts with the activity.

OnDestroy

OnCreate () is the first method to be executed in the life cycle, and OnDestroy () is the last method of execution in the life cycle. The system calls the OnDestroy () method in activity as the end signal, and the activity instance is removed from the system memory.

Most apps do not need to implement this method, because before activity calls OnDestroy (), clear memory operations should be performed in both OnPause () and OnStop () methods. But if the activity in the thread is in OnCreate () or some long-running resources, if not properly shut down, will cause a memory leak! It is time to turn them off in the final OnDestroy () method.

@OverridepublicvoidonDestroy() {    super.onDestroy(); }

After the system calls the OnPause () and OnStop () methods, it calls OnDestroy ().
In addition to a situation , the finish () method is called in OnCreate ().
Sometimes, for example, when an activity executes a temporary decision to start another activity, the finish () method is called in OnCreate (). In this case, the system calls the OnDestroy () method immediately, and no longer passes through the other callback methods of the life cycle.

OnPause () and Onresume ()

When users use the app, the foreground activity is sometimes obscured by other components, which can cause activity to pause. For example, when a prompt dialog box opens, activity pauses. Although part of the activity can still be seen, the activity is paused and no action is taken. If the activity is completely obscured and invisible, it stops. Will enter the stopped state.

When activity enters the paused state, the system invokes OnPause () in the activity, such as pausing the video, or temporarily saving some information. When the user returns from the paused state to the current activity, the system calls the Onresume () method back to the resumed state.

When the system calls OnPause (), the Activity section is visible. In most cases, however, the user leaves the current activity, enters the stopped state, and finally executes the OnDestroy () method. So, there are a few things to do in OnPause ():

1. Stop the animation that consumes the CPU or the operation that is running.
2, submit unsaved changes, such as draft mail/3, release system resources, such as radio receivers, GPS, or when activity is paused, and users do not need to use the resources

For example, the app uses a camera, so the OnPause () method is a very suitable place to release it

@OverridepublicvoidonPause() {    super.onPause();  //首先调用父类的方法    // 释放资源,因为其他的Activity可能需要用到它    ifnull) {        mCamera.release();        null;    }}

Note that you do not perform the operation of the database in the OnPause () method because it makes it slow to jump to the next activity.
Perform some relatively simple operations on onpause () so that you can quickly jump to the next activity. When activity is stopped, the activity instance is placed in memory, and when the activity resumes, it is called again, and no more activity instances need to be recreated.

It is necessary to know that each time the system calls the Onresume () method, the activity will return to the foreground, which also includes the first time the instance was created.

Some components that are freed in OnPause () should be initialized in the Onresume () method, as well as the components needed for each recovery, such as some starting animations and required components.

The following onresume () corresponds to the above OnPause () example, initializing the camera that was released in the Pasued state.

@OverridepublicvoidonResume() {    super.onResume();      ifnull) {        // 初始化相机的操作    }}

Android Growth Path (3)--activity life cycle (1)

Related Article

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.