Android activity Detailed (lifecycle, start activity in various ways, state save, complete exit, etc.) _android

Source: Internet
Author: User

One, what is activity?

Simply put: An activity is an interactive interface that is full of windows or floating over other windows. In an application, which is typically composed of multiple activity, a master activity is specified in the Manifestxml, as set

<actionandroid:name= "Androidintentactionmain"/>

When the program is first run, the user will see the activity, which can be done by initiating other actions. This current activity will stop when other activity is started, the new one will be pushed into the stack, and the user focus can be obtained, and then it will be able to operate on it. All know that the stack is the principle of advanced, then when the user presses the Back button, the current activity is destroyed, the previous activity resumed.

Second, activity life cycle

First look at the following figure:

This diagram does not say much more, below we use an example to explain the problem. To create a new project, write the following code:

<span style= "FONT-SIZE:18PX;" 
>package Comandroidttxactiitylifedemo; 
Import androidappactivity; 
Import Androidosbundle; 
Import Androidutillog; 
Import androidviewkeyevent; 
   
  public class Activitylifedemo extends activity {Private final static String tag= "Activitylifedemo"; 
    @Override public void OnCreate (Bundle savedinstancestate) {superoncreate (savedinstancestate); 
     
    Setcontentview (Rlayoutmain); 
  Logi (TAG, "onCreate"); 
    @Override protected void OnStart () {Logi (TAG, "OnStart"); 
  Superonstart (); 
    @Override protected void Onrestart () {Logi (TAG, "Onrestart"); 
  Superonrestart (); 
    @Override protected void Onresume () {Logi (TAG, "Onresume"); 
  Superonresume (); 
    @Override protected void OnPause () {Logi (TAG, "OnPause"); 
  Superonpause (); 
    @Override protected void OnStop () {Logi (TAG, "onStop"); 
  Superonstop (); } @Override protected void OnDestroy () { 
    Logi (TAG, "OnDestroy"); 
  Superondestroy (); 
 }} </span>

The code is simple, involving only one activity, some user's actions, and we look at the activity's lifecycle process by recording operations and printing logs.

1, Operation

See the following print log:

08-31 08:46:916:info/activitylifedemo (312): OnCreate
08-31 08:46:916:info/activitylifedemo (312): OnStart
08-31 08:46:916:info/activitylifedemo (312): Onresume

2, press the Back button:

08-31 09:29:396:info/activitylifedemo (354): OnPause
08-31 09:29:216:info/activitylifedemo (354): OnStop
08-31 09:29:216:info/activitylifedemo (354): OnDestroy

3, long press the home button, pop-up recently opened the application, click Activitylifedemo

08-31 08:51:916:info/activitylifedemo (312): OnCreate
08-31 08:51:916:info/activitylifedemo (312): OnStart
08-31 08:51:936:info/activitylifedemo (312): Onresume

4, press the home button

08-31 08:53:676:info/activitylifedemo (312): OnPause
08-31 08:53:796:info/activitylifedemo (312): OnStop

5. Click to open in Alllist

08-31 08:54:286:info/activitylifedemo (312): Onrestart
08-31 08:54:286:info/activitylifedemo (312): OnStart
08-31 08:54:296:info/activitylifedemo (312): Onresume

Through the log information, we can see. The start of the activity: oncreate-onstart-onresume; When the key is returned: Onpause-onstop-ondestroy As mentioned above, when the return key is pressed, the activity pops up the stack and the program is destroyed. Indeed, when we open again, the startup process goes back to Oncreate-onstart-onresume. OK, press the home key after startup, go back to launcher, check the printing information: onpause-onstop, open again the running process: Onrestart-onstart-onresume.

We form the lifecycle of activity through various operations of activities, and we see that the relevant callback methods are received regardless of how the activity is done, so that we can write work through these callback methods during development, such as releasing some heavyweight objects , network connections, database connections, file reads, and so on.

The following are detailed instructions for each method:

OnCreate (): When an activity is first created, it is invoked. In this method you need to complete all the normal static settings, such as creating a view, binding list of data, and so on. If the activity state is captured, the Bundle object passed in by this method will store the current state of the activity. The OnStart () method is typically invoked after the method is called.

Onrestart (): This method is called when the activity is stopped and restarted. Subsequent calls to the OnStart method.

OnStart () This method is invoked when the activity is visible to the user. If the activity returns to the foreground, then call Onresume () and call OnStop () if the activity is hidden.

Onresume (): This method is called before the activity begins interacting with the user. At this point the activity is at the top of the activity stack and accepts input from the user. Subsequent calls to the OnPause () method.

OnPause (): This method is called when the system is ready to start resuming other activity. This method is often used to commit some unsaved changes to persistent data, stop some animations or some other CPU-consuming operations, and so on. Whatever you do inside the method needs to be done quickly, because the next activity will not be able to recover if it does not return. If the activity returns to the foreground, Onresume () will be invoked, and OnStop () will be invoked if the activity becomes invisible to the user.

OnStop (): This method is invoked when the activity is not visible to the user. This method may be invoked because the current activity is being destroyed, or another activity (an existing activity or a new activity) has been restored and is being prepared to overwrite it. If the activity is preparing to return to Onrestart when it interacts with the user, call OnDestroy if the activity is being freed.

OnDestroy (): This method is called before the activity is destroyed. This is the last call that the activity can receive. This method may be invoked because someone calls the finish method to cause the current activity to shut down, or the system temporarily releases an instance of the activity in order to protect memory. You can use the Isfinishing method to distinguish between these two different situations.

Iii. How to start a new activity?

To start a new activity, we can start by invoking the startactivity in the context. Like this:

<span style= "FONT-SIZE:18PX;" >intent Intent = new Intent (this, activitydemoclass); 
StartActivity (Intent); Activitydemo is the activity class that needs to be started 

You can start a new activity by using the above method, but what if I'm going to pass data from the current activity to the new activity? Very simple:

<span style= "FONT-SIZE:18PX;" >intent Intent = new Intent (this,activitydemoclass); 
Bundle Bundle = new Bundle (); 
Bundleputboolean ("Bool_key", true); 
Intentputextras (bundle); 
StartActivity (Intent); 

Also, sometimes we need to start an activity with a return value, simply by passing the value to the activity that started it when the newly initiated activity returns, like this:

<span style= "FONT-SIZE:18PX;" >intent Intent = new Intent (activitylifedemothis,revalueactivityclass); 
Startactivityforresult (Intent, 0x1001); 

Activitylifedemo is the current activity, starting revalueactivity, we need to get revalueactivity back in Activitylifedemo. Then it must be written in the revalueactivity:

<span style= "FONT-SIZE:18PX;" >intent Intent = new Intent (); 
Intentputextra ("Revalue_key", "haha-revalueactivity"); 

So where does the "Revalue_key" value get? The Onactivityresult method must be rewritten to determine the Requestcode by judging

<span style= "FONT-SIZE:18PX;" >if (requestcode==0x1001) { 
      String str = Datagetstringextra ("Revalue_key"); 
      Logi (TAG, "The value returned is:" +str); 
    } 

OK, please see the code in detail. Download Address: Http://xiazai.jb51.net/201611/yuanma/ActivityLifeDemo_jb51.rar

Iv. preservation of activity running status

Note the following points by overriding the Onsaveinstancestate () method to implement the running status of the activity:

1 as the activity object is paused or stopped, it remains in memory, and its member information and current state are active, so that the state of the activities can be saved so that the changes made by the user are saved in memory

2 When the system reclaims the memory and destroys the activity, it cannot save its state, so it is necessary to call the Onsaveinstancestate () method to save the state.

3 Many situations do not need to maintain state information, such as press the return key to close the program directly, so it is not guaranteed to call onsaveinstancestate. If this method is invoked, it is typically preceded by a OnStop method and may be invoked after OnPause. However, even if you do not do anything or do not implement the Onsaveinstancestate () method, your activity status can be recovered through the Onsaveinstancestate method that is implemented by default in the active class. In particular, the Onsaveinstancestate method is called by default for views in the layout, and in this method allows each view to provide any information it needs to recover. Almost every widget in the Android framework implements this approach as appropriate.

Note: Because the Onsaveinstancestate method is not necessarily invoked, you should only use it to save the state of the transformation process of some activity (i.e. the state of the UI) and not to hold persistent data. But you can use the OnPause method to save persistent data when the user leaves the activity, such as data that needs to be saved to the database.

There is a good way to test the ability of an application to save state by simply rotating your device to change the direction of the screen. Because when the screen direction changes, the system destroys the activity and creates a new one, in order to provide a possible alternative resource for the new direction. For this reason, it is particularly important that your activity can be saved when it is recreated, because users often rotate the screen when they use the application.

V. Complete withdrawal of procedures

With the above introduction, we know that when we click the back key, the program calls the OnDestroy method, the program exits, but we look at its process and find that the activity is still running after the OnDestroy method is invoked. Even after you call the finish () method, the program can see it in the process. You can implement a complete exit of the program in the following way:

<span style= "FONT-SIZE:18PX;" >intent Intent = new Intent (); 
Intentsetclass (context,mainactivityclass); 
Intentsetflags (intentflag_activity_clear_top); 
Intentputextra ("flag", exit_application); 
Contextstartactivity (intnet);  

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.