Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Activity 的 SingleTask 模式:onNewIntent 的用法與原理

編輯:關於 Android 程式設計

近來翻看別人的程式碼時,注意到一個名為 onNewIntent 的方法,於是決定深入研究它的用途與觸發時機。本文透過實驗,把 singleTask 模式下 onNewIntent 的行為梳理清楚。

一、onNewIntent 的調用時機

在一個名為 IntentActivity 的頁面中,我們重載了完整的生命週期方法:onCreate、onStart、onRestart、onResume、onPause、onStop、onDestroy,以及本文的主角 onNewIntent,藉此觀察它們的呼叫順序。

當其他應用發送一個 Intent(例如以自訂 scheme 觸發 VIEW 動作)時:

Uri uri = Uri.parse("philn://blog.163.com");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);

若 IntentActivity 尚未啟動,系統會依序呼叫 onCreate → onStart → onResume。

二、接收 Intent 的宣告

關鍵在於把 Activity 的 launchMode 設為 singleTask,並配置對應的 intent-filter:

<activity android:name=".IntentActivity"
    android:launchMode="singleTask"
    android:label="@string/testname">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="philn"/>
    </intent-filter>
</activity>

三、棧頂複用時的執行順序

如果 IntentActivity 已存在於任務堆疊頂端(此時它處於 onPause、onStop 狀態),其他應用再次發送 Intent 時,執行順序會變成:

onNewIntent → onRestart → onStart → onResume

注意,此時系統「不會」再呼叫 onCreate,而是改呼叫 onNewIntent。這正是 singleTask 模式的核心特性:當系統中已存在相同實例時,會把請求直接發送到該實例上,避免重複創建。

四、實務上的注意事項

在 onNewIntent 中處理新資料時,有一個容易忽略的細節:必須呼叫 setIntent(intent),否則後續透過 getIntent() 拿到的會是舊的 Intent。

protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent); // 必須保存新的 intent,否則 getIntent() 會回傳舊的
    processExtraData();
}

此外,系統可能隨時殺掉背景的 Activity。一旦發生這種情況,再次啟動時系統會改走 onCreate 而非 onNewIntent。因此一個穩健的做法,是在 onCreate 與 onNewIntent 中呼叫同一個處理資料的方法:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    processExtraData();
}

protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
    processExtraData();
}

private void processExtraData() {
    Intent intent = getIntent();
    // 在這裡統一使用收到的資料
}

把資料處理邏輯抽成獨立方法,兩處共用,就能從容應對「實例已存在」與「實例被銷毀重建」這兩種截然不同的情境,確保行為一致。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved