Specific explanation of activity (lifecycle, starting activity in various ways, saving status, and completely exiting)

Source: Internet
Author: User
1. What is activity?

Simply put, activity is an interactive interface that is filled with the entire form or suspended on other forms. In an application, a main activity is usually composed of multiple activities. A main activity is specified in manifest. xml. For example

<Actionandroid: Name = "android. Intent. Action. Main"/>

When the program is executed for the first time, the user will see the activity, which can be related to the operation by starting other activities. When other activities are started, the current activity will stop, and the new activity will be pushed into the stack. At the same time, the user focus will be obtained, and then the activity can be operated. We all know that the stack is an advanced post-release principle. When you press the back key, the current activity is destroyed and the previous activity is restored again.

Ii. Activity Lifecycle

First look:

I will not talk more about this image. Here we will use an instance to illustrate the problem. Create a project and write the following code:

package com.android.ttx.actiitylifedemo;import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.view.KeyEvent;public class ActivityLifeDemo extends Activity {private final static String TAG="ActivityLifeDemo";    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                Log.i(TAG, "onCreate");    }@Overrideprotected void onStart() {Log.i(TAG, "onStart");super.onStart();}@Overrideprotected void onRestart() {Log.i(TAG, "onRestart");super.onRestart();}@Overrideprotected void onResume() {Log.i(TAG, "onResume");super.onResume();}@Overrideprotected void onPause() {Log.i(TAG, "onPause");super.onPause();}@Overrideprotected void onStop() {Log.i(TAG, "onStop");super.onStop();}@Overrideprotected void onDestroy() {Log.i(TAG, "onDestroy");super.onDestroy();}}

The code is very easy. It only involves an activity. For some user operations, we can record operations and print logs to see the activity lifecycle process.

1. Execute
See the following print log:
08-31 08:46:53. 916: INFO/activitylifedemo (312): oncreate
08-31 08:46:53. 916: INFO/activitylifedemo (312): onstart
08-31 08:46:53. 916: INFO/activitylifedemo (312): onresume
2. Press the return button:
08-31 09:29:57. 396: INFO/activitylifedemo (354): onpause
08-31 09:29:58. 216: INFO/activitylifedemo (354): onstop
08-31 09:29:58. 216: INFO/activitylifedemo (354): ondestroy
3. Press the Home Key to display recently opened applications. Click activitylifedemo.
08-31 08:51:46. 916: INFO/activitylifedemo (312): oncreate
08-31 08:51:46. 916: INFO/activitylifedemo (312): onstart
08-31 08:51:46. 936: INFO/activitylifedemo (312): onresume
4. Press the Home Key.
08-31 08:53:32. 676: INFO/activitylifedemo (312): onpause
08-31 08:53:33. 796: INFO/activitylifedemo (312): onstop
5. Click Open in alllist.
08-31 08:54:14. 286: INFO/activitylifedemo (312): onrestart
08-31 08:54:14. 286: INFO/activitylifedemo (312): onstart
08-31 08:54:14. 296: INFO/activitylifedemo (312): onresume

We can see through the log information. Activity startup process: oncreate-onstart-onresume; when the return key is down: 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 it again, the START process returns to oncreate-onstart-onresume. OK. Press the Home Key and return to launcher to view the message print: onpause-onstop. the execution process is onrestart-onstart-onresume.

Through various operations on the activity, the lifecycle of the activity is formed. We can see that no matter what operations are performed on the activity, the relevant callback method will be received, in the development process, we can use these callback methods to write jobs, such as releasing heavyweight objects, network connections, database connections, and file reads.

The following describes the methods:

Oncreate (): called when the activity is created for the first time. In this method, you need to complete all normal static settings, such as creating a view and binding the list data. If the status of the activity can be captured, the bundle object passed in by this method will store the current status of the activity. After this method is called, The onstart () method is usually called.

Onrestart (): This method is called when the activity is started again after it is stopped. It may call the onstart method.

Onstart () à this method is called before the activity is visible to the user. Assume that the activity is returned to the foreground, then onresume () is called. if the activity is hidden, onstop () is called ()

Onresume (): This method is called before the activity starts to interact with the user. At this time, the activity is at the top of the activity stack and receives user input. It may call the onpause () method.

Onpause (): This method is called when the system is preparing to start resuming other activities. This method is usually used to submit some unsaved changes to persistent data, stop some animations or other CPU-consuming operations. No matter what operation is performed in this method, it must be completed at a high speed. If it is not returned, the next activity cannot be restored. Assume that onresume () is called when the activity is returned to the foreground. If the activity becomes invisible to the user, onstop () is called ().

Onstop (): This method is called when the activity is invisible to the user. This method may be called because the current activity is being destroyed or another activity (an existing activity or a new activity) has been restored and is being overwritten. Assume that onrestart is called when the activity is preparing to return and interact with the user. if the activity is being released, ondestroy is called.

Ondestroy (): This method is called before the activity is destroyed. This is the last call that activity can receive. This method may be called because the finish method is called to disable the current activity, or the system calls this method to protect the memory for temporarily releasing the instance of this activity. You can use the isfinishing method to differentiate the two different situations.

3. How to start a new activity?

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

Intent intent = new intent (this, activitydemo. Class); startactivity (intent); // activitydemo is the activity class to be started.

The above method can be used to start a new activity, but suppose I want to transfer data from the current activity to the new activity? Very easy:
Intent intent = new Intent(this,ActivityDemo.class);Bundle bundle = new Bundle();bundle.putBoolean("bool_key", true);intent.putExtras(bundle);startActivity(intent);

In addition, sometimes we need to start an activity with a returned value. Simply put, we need to pass the value to the activity that starts the activity when a newly started activity is returned, as shown in the following code:

Intent intent = new Intent(ActivityLifeDemo.this,RevalueActivity.class);startActivityForResult(intent, 0x1001);

Activitylifedemo is the current activity. To start revalueactivity, we need to obtain the value passed back by revalueactivity in activitylifedemo. In revalueactivity, you must write as follows:

Intent intent  = new Intent();intent.putExtra("revalue_key","haha-revalueActivity");setResult(0x1001, intent);
Where can I obtain the value of "revalue_key? The onactivityresult method must be rewritten and determined by inferring requestcode.

If (requestcode = 0x1001) {string STR = data. getstringextra ("revalue_key"); log. I (TAG, "returned value:" + Str );}

Okay. For more information, see the code. : Http://download.csdn.net/detail/tangcheng_ OK /3580700

 

4. Save the activity execution status

You can override the onsaveinstancestate () method to implement the activity execution status. Note the following points:

1) because the activity object is paused or stopped, it is still stored in the memory. Its member information and current status are both active, so the activity status can be saved at this time, so that the changes made by the user are stored in the memory.

2) When the system recycles the memory and destroys the activity, its status cannot be saved. Therefore, you must call the onsaveinstancestate () method to save the status.

3) In many cases, you do not need to keep the status information. For example, if you press the return key to directly close the program, you cannot guarantee that the onsaveinstancestate will be called. If this method is called, it is usually called before the onstop method and after the onpause method. Even so, even if you do not perform any operations or do not implement the onsaveinstancestate () method, your activity status can be restored through the onsaveinstancestate method implemented by default in the activity class. In particular, the onsaveinstancestate method is called by default for the view in the layout, and in this method, each view is allowed to provide whatever information it needs to be restored. Almost every widget in the android framework implements this method as needed.

Note: Because the onsaveinstancestate method may not be called, you should simply use it to save the status of some activity conversion processes (that is, the UI status), rather than to save permanent data. However, you can use the onpause method to save permanent data when the user leaves the activity. For example, you need to save the data to the database.

There is a good way to test the application's storage status, that is, simply rotating your device to change the screen direction. When the screen direction changes, the system will destroy the activity and create a new one to provide a possible replacement resource for the new direction. For this reason, it is especially important that your activity can be saved when it is created again, because users often rotate the screen when using the application.

The above content has been taken into consideration.

5. Completely exit the program

Through the above introduction, we know that when the back key is clicked, the program calls the ondestroy method and the program exits, but we can view its process, after ondestroy is called, the activity is still being executed. Even after the finish () method is called, the program can see it in the process. You can exit the program in the following ways:

Intent intent = new Intent();Intent.setClass(context,MainActivity.class);intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);intent.putExtra(“flag”,EXIT_APPLICATION);context.startActivity(intnet); 

OK. This is the next 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.