編輯:關於 Android 程式設計
本文以實例深入分析 Android 中 Activity 的完整生命周期。以下內容供大家參考。
在 Android 裡,每個 Activity 都有自己的一套生命周期。理解這些知識,能幫助我們在日後寫程式時,更從容地應對各種常見錯誤。這篇文章較長,但值得細細閱讀。本文暫不涉及太多 Activity 棧的細節,主要聚焦於 Activity 自身的生命周期。
1 Activity:官方定義為「一個應用組件,它提供一個讓用戶與之互動以完成某項操作的畫面,例如撥打電話、拍照、發送郵件或查看地圖。每個 Activity 都會獲得一個視窗,用於繪製其使用者介面。」簡單說,Activity 就是用戶用來互動的每一個視窗,代表用戶當前正在進行的一項操作。
2 back-stack(返回棧):用戶透過應用啟動器打開一個 Activity A,A 會被壓入棧頂;若 A 再啟動新的 Activity B,此時 A 會呼叫 onStop,由系統維護它的狀態。當用戶按下返回鍵時,返回棧會執行 pop 操作,並呼叫 A 的 onResume()。具體的進出棧細節,之後會再詳述。
3 Tasks(任務):當用戶處於某個 Activity(例如名稱為「TaskOne」的任務)中,按下 HOME 鍵回到桌面後,若再打開新應用,就會建立一個新 Task。一個返回棧就代表一個 Task。不同程式的 Activity 可以壓入同一個棧中組成一個 Task——比如你的程式啟動了系統自帶的傳簡訊 Activity,用戶的感覺就像是「傳簡訊」成了你程式的一個功能。
註:以上皆為系統預設行為。有兩種方式可以改變 Activity 的行為:一是在 B 的 manifest 中設定,二是在發起 Intent 時指定啟動目標的設定,其中 Intent 的優先級高於 manifest.xml,而且有些模式並不一定同時存在於這兩種方式中。
Android 的生命周期包含 onCreate、onStart、onRestart、onResume、onPause、onStop、onDestroy 等方法,Activity 在生命周期中會呼叫這些方法來執行不同狀態對應的操作。下面逐一介紹。
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().
當 Activity 第一次被建立時呼叫。你應該在這個方法裡進行所有的靜態初始化,例如建立 views、透過 setContentView 設定介面、向清單綁定數據等。若存在已保存的狀態,該方法還會提供一個包含 Activity 最近狀態的 Bundle。onStart 總是在此方法之後被呼叫。
Called after your activity has been stopped, prior to it being started again. Always followed by onStart().
在 Activity 停止之後、重新啟動之前呼叫,之後緊接著 onStart。
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().
當 Activity 即將與用戶互動時呼叫。此刻它位於 Activity 棧的頂端,接收用戶輸入,之後總是在 onPause 之前被呼叫。
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 consuming CPU, 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.
當系統即將恢復上一個 Activity 時呼叫。通常用來提交尚未保存的數據、停止動畫及其他可能消耗 CPU 的操作。此方法的實作必須很快,因為下一個 Activity 要等到它返回後才會恢復。若 Activity 回到前台,此方法之後呼叫 onResume;若 Activity 變得不可見,則之後呼叫 onStop。
Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.
當 Activity 對用戶不再可見時呼叫,因為另一個 Activity 已恢復並覆蓋了它。這可能是因為啟動了新 Activity、既有 Activity 回到前台,或當前 Activity 即將被銷毀。若 Activity 要返回前台,之後呼叫 onRestart;若即將消亡,則之後呼叫 onDestroy。
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.
這是 Activity 被銷毀前收到的最後一個回調。觸發情況有兩種:一是 Activity 即將結束(有人呼叫了 finish()),二是系統為了釋放空間而暫時銷毀該實例。可用 isFinishing() 方法來區分這兩種情況。下面的 demo 就會演示這個判斷。
下圖是官方對生命周期的示意:

接下來看一個我寫的演示例子。
MainFest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://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>
布局檔案 main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://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="https://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"); } } 下面是演示結果。操作過程是:先啟動 ActivityDemoActivity。

然後點擊按鈕進入 Activity01。

(可見舊的 Activity 會先進入暫停且不會被釋放,本質上是一個新 Activity 壓棧的過程;接著新 Activity 啟動,先 onCreate 再 onStart。作者在此處的 Log 文字寫錯了,細心的朋友應該注意到了:當舊 Activity 不可見時,才會呼叫它的 onStop。)
再按返回鍵回到 ActivityDemoActivity。

(返回後,位於棧頂的 Activity01 會執行彈棧操作,隨後將被 destroy。)
再按返回鍵回到桌面。

其實並不複雜,只是作者寫得較長,但基本上完整呈現了 Activity 的生命周期。希望本文對大家的 Android 開發有所幫助。
聊聊 Android 視圖滾動狀態監聽與嵌套滾動思路
在自定義控制項或互動效果中,判斷視圖是否還能繼續滑動,是很實用的能力。Android 的 ViewCompat 提供了 canScrollVertically 與 can
Android 下拉刷新 ListView 實作教學——RTPullListView(附範例)
下拉刷新已經成為越來越多 App 的標準互動,成了使用者根深柢固的操作習慣——遇到列表,手指很自然就往下一拉。本文要介紹如何在 Android 上實作下拉刷新,參考了 G
透透徹徹搞懂 LinearLayout 的 layout_weight 分配規則
layout_weight 只在 LinearLayout 中生效,這是第一個要記住的前提。 Google 的明確建議是:一旦設定了 layout_weight,對應的
用 Volley 解決列表圖片加載:ImageRequest、ImageLoader 與 NetworkImageView 三種方案
搜芽的開發這幾天進度相當快,唯一美中不足的是網路圖片的加載環節。我先試過兩條路,都不太理想: 第一套是沿用迅雷動漫的圖片加載方案。那也是個開源庫,但不知道是我不會用還是