Home >Java >javaTutorial >Activity life cycle when Android switches between horizontal and vertical screens

Activity life cycle when Android switches between horizontal and vertical screens

高洛峰
高洛峰Original
2017-01-07 16:15:191778browse

The example of this article analyzes the complete life cycle of activity in Android programming. Share it with everyone for your reference, the details are as follows:

Activities in android have their own life cycles. Learning this knowledge can help us better understand some of the errors we encounter when writing programs in the future. . This article is very long, I hope it won’t take up everyone’s time~

Today I won’t cover too much about the activity stack, but mainly about the life cycle of the activity itself

Distinguish between several concepts

1 Activity The official explanation is “An Activity is an application component that provides a screen with which users can interact in order to do something, such as dial the phone, take a photo, send an email, or view a map. Each activity is given a window in which to draw its user interface. "That is, every window the user uses to interact, an operation the user is currently performing.

2 back-stack The user will start an activity A through the application launcher by touching the program. The started activity A will be pushed to the top of the stack. If the current activity A starts a new activity B, then this When A calls the onStop function, the system will maintain this activity information. When the user presses the back key, the back stack will perform a pop operation and call A's onResume(). The specific details of popping and popping the stack will be introduced in detail later.

3 Tasks When the user is in an activity: Activity A is named "TaskOne application", press the HOME key and the user returns to the launcher. At this time, if the user touches a new application again, create a new application A Task and a back stack represent a task. Activities from different programs can be pushed into the same stack, which means they can form a task. For example, your program starts a text messaging activity that comes with the system, giving the user It feels like sending text messages is a function in your program.

Note: The above behaviors are the default settings of the system. There are two ways to change the behavior of the activity. One is to add A to start B. In B's manifest settings, change the behavior. The other is to specify the activity settings to be started in the intent initiated by the Activity. The priority of the intent is higher than the manifest.xml file, and some modes do not exist at the same time. In two ways.

The life cycle of android includes onCreate onStart onRestart onResume onPause onStop onDestroy. Activity will call the above methods during the declaration cycle to perform operations corresponding to different states. The calling time of each method is introduced below.

onCreate() The activity cannot be terminated in this state
Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.

Always followed by onStart().
//You should call it when the activity is first created. Do all static creation in this method, create views, bind data to lists (via the setContnetView method), etc. This method also provides you with a bundle that contains the activity's most recent state.

onRestart() is always called after this method. The activity cannot be terminated
Called after your activity has been stopped, prior to it being started again.
Always followed by onStart()
//Called after your activity is stopped and called before restarting

onResume() The activity cannot be terminated in the state
Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.
Always followed by onPause().
//Called when the activity will be started to interact with the user. At this moment, your activity is at the top of the activity stack and is used for user input. It will always be called after onPause.

onPause() The activity cannot be terminated in this state, except for the android HoneyComb system.
Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be CPU consuming, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns.
Followed by either onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user.

//When the system is about to restart It is called when the previous activity (I don’t understand, my understanding is: it is called when the current activity wants to start a new activity). A typical application is used to submit unsaved data to the current data, (meaning Just save data updates), stop animations and other operations that may consume CPU. The implementation of this method must be fast because the next activity will not be restarted until this method returns.

When the activity changes from back (the translation background is not suitable) to front (the state of interacting with the user), the onResume method will be called after the onPause method

When the activity becomes invisible, the onStop method will be called after onPause

onStop() times the activity can be terminated
Called when the activity is no longer visible to the user , because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed.
Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.

//Called when the activity is no longer visible to the user because another activity has Restarts and overwrites the current activity (on the stack). When a new activity is started, or an existing activity returns to the foreground, or the current activity is destroyed. If the activity wants to return to the foreground and interact with the user, the onReatart method will be called after this method. If the current activity is going to die, the onDestroy method will be called after this method.

onDestroy() The activity can be terminated in this state several times.
The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.

This is the last method received when your activity is killed. There are two scenarios for calling this method: one is that the activity is about to be completed, which can be passed. Call the finish method. Instead, the system destroys the activity instance to free up space. This method is often used in the onPause method to determine whether the activity is paused or terminated. The following demo will demonstrate this. Function.

The picture below is a life cycle demonstration on the official website

Activity life cycle when Android switches between horizontal and vertical screens

##Okay, let’s take a look at a demonstration example I wrote,

MainFest.xml

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="uni.activity"
   android:versionCode="1"
   android:versionName="1.0"> 
  <uses-sdk android:minSdkVersion="7" /> 
  <application android:icon="@drawable/icon" android:label="@string/app_name"> 
    <activity android:name=".ActivityDemoActivity"
         android:label="@string/app_name"> 
      <intent-filter> 
        <action android:name="android.intent.action.MAIN" /> 
        <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
    </activity> 
    <activity android:name=".Activity01"
         android:label="@string/app_name"> 
    </activity> 
  </application> 
</manifest>

Layout file main.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  > 
<TextView 
  android:layout_width="fill_parent" 
  android:layout_height="wrap_content" 
  android:text="@string/hello"
  /> 
 <Button 
  android:id="@+id/Button_A"
  android:text="GO to activity 2"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  /> 
</LinearLayout>

activity01.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  > 
<TextView 
  android:layout_width="fill_parent" 
  android:layout_height="wrap_content" 
  android:text="@string/hello"
  /> 
 <Button 
  android:id="@+id/Button_A"
  android:text="GO to activity 2"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  /> 
</LinearLayout>

String.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
  <string name="hello">Hello World, ActivityDemoActivity!</string> 
  <string name="app_name">ActivityDemo</string> 
  <string name="activity01">this is activity 01</string> 
</resources>

ActivityDemoActivity.java

/* 
 * @author octobershiner 
 * 2011 07 29 
 * SE.HIT 
 * 演示完整的activity的声明周期,以及isFinish方法的调用 
 * 此activity为程序入口activity 
 * */ 
package uni.activity; 
import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
public class ActivityDemoActivity extends Activity { 
  /** Called when the activity is first created. */
  private static final String TAG = "demo"; 
  private Button button_A; 
  @Override
  public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    button_A = (Button)this.findViewById(R.id.Button_A); 
    button_A.setOnClickListener(new myButtonListener()); 
  } 
  private class myButtonListener implements OnClickListener{ 
    @Override
    public void onClick(View v) { 
      // TODO Auto-generated method stub 
      Intent intent = new Intent(); 
      intent.setClass(ActivityDemoActivity.this, Activity01.class); 
      ActivityDemoActivity.this.startActivity(intent); 
      //感兴趣的朋友可以取消下面的代码注释,来测试finish方法的使用,会发现第一个activity会被强制终止 
      //ActivityDemoActivity.this.finish(); 
    } 
  }; 
  protected void onStart(){ 
    super.onStart(); 
    Log.i(TAG, "The activityDemo state---->onStart"); 
  } 
  protected void onRestart(){ 
    super.onRestart(); 
    Log.i(TAG, "The activityDemo state---->onReatart"); 
  } 
  protected void onResume(){ 
    super.onResume(); 
    Log.i(TAG, "The activityDemo state---->onResume"); 
  } 
  protected void onPause(){ 
    super.onPause(); 
    //调用isFinishing方法,判断activity是否要销毁 
    Log.i(TAG, "The activityDemo state---->onPause"); 
    if(isFinishing()){ 
      Log.w(TAG, "The activityDemo will be destroyed!"); 
    }else{ 
      Log.w(TAG, "The activityDemo is just pausing!"); 
    } 
  } 
  protected void onStop(){ 
    super.onStop(); 
    Log.i(TAG, "The activityDemo state---->onStop"); 
  } 
  protected void onDestroy(){ 
    super.onDestroy(); 
    Log.i(TAG, "The activityDemo state---->onDestroy"); 
  } 
}

Activity01.java

/* 
 * @author octobershiner 
 * 2011 07 29 
 * SE.HIT 
 * 演示完整的activity的声明周期,以及isFinish方法的调用 
 * 此activity可由ActivityDemoActivity启动 
 * */
package uni.activity; 
import android.app.Activity; 
import android.os.Bundle; 
import android.util.Log; 
public class Activity01 extends Activity{ 
  private static final String TAG = "demo"; 
  @Override
  protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity01); 
    Log.d(TAG, "The activity01 state---->onStart"); 
  } 
   protected void onStart(){ 
      super.onStart(); 
      Log.d(TAG, "The activity01 state---->onStart"); 
    } 
    protected void onRestart(){ 
      super.onRestart(); 
      Log.d(TAG, "The activity01 state---->onReatart"); 
    } 
    protected void onResume(){ 
      super.onResume(); 
      Log.d(TAG, "The activity01 state---->onResume"); 
    } 
    protected void onPause(){ 
      super.onPause(); 
      Log.d(TAG, "The activity01 state---->onPause"); 
      //调用isFinishing方法,判断activity是否要销毁 
      if(isFinishing()){ 
        Log.w(TAG, "The activity01 will be destroyed!"); 
      }else{ 
        Log.w(TAG, "The activity01 is just pausing!"); 
      } 
    } 
    protected void onStop(){ 
      super.onStop(); 
      Log.d(TAG, "The activity01 state---->onStop"); 
    } 
    protected void onDestroy(){ 
      super.onDestroy(); 
      Log.d(TAG, "The activity01 state---->onDestroy"); 
    } 
}

The following is the result of the demonstration,

The operation process is: start ActivityDemoActivity

Activity life cycle when Android switches between horizontal and vertical screens

and click The button enters Activity01

Activity life cycle when Android switches between horizontal and vertical screens

(it can be seen that the activity is paused first and will not be released. It is actually a process of pushing a new activity onto the stack, and then the new activity starts. It should be onCreate and then onStart. I The print statement is wrong. Attentive friends should have seen that when the old activity is not visible, its onStop method is called)

Then press the return key to return to ActivityDemoActivity

(After returning, it is on the stack The top activity01 will perform the pop-up operation, and the display will be destroyed)

Press the return key to return to the desktop

Activity life cycle when Android switches between horizontal and vertical screens

It’s actually not complicated. It's a bit long to write, but it basically shows the complete life cycle of the activity.

I hope this article will be helpful to everyone in Android programming.

For more articles related to the life cycle of Activity when switching between horizontal and vertical screens in Android, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn