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

Android 中 Intent 與 PendingIntent 的區別详解

編輯:關於 Android 程式設計

Intent 英文原意是「意圖」,而 Pending 表示即將發生或即將到來的事情。PendingIntent 這個類別,正是用來處理即將發生之事的。例如在通知(Notification)中用於跳轉頁面,但並不是馬上跳轉。

Intent 與 PendingIntent 的核心差異

Intent 是即時啟動的,它會隨所在的 Activity 消失而消失。PendingIntent 則可以看作對 Intent 的包裝,通常透過 getActivity、getBroadcast、getService 來取得其實例。此時當前的 Activity 並不會馬上啟動它所包含的 Intent,而是在外部執行 PendingIntent 時才呼叫其中的 Intent。

正因為 PendingIntent 中保存了當前 App 的 Context,它賦予了外部 App 一種能力:讓外部 App 能如同當前 App 一般執行 PendingIntent 裡的 Intent,就算執行時當前 App 已經不存在,也能透過存在 PendingIntent 裡的 Context 照樣執行。此外,它還能處理 Intent 執行後的操作,常與 AlarmManager 和 NotificationManager 一起使用。

簡單來說,Intent 一般用於 Activity、Service、BroadcastReceiver 之間傳遞資料;而 PendingIntent 一般用於 Notification 上,可理解為「延遲執行的 Intent」,本質上是對 Intent 的一層包裝。

應用示例一:通知跳轉

在建立 Notification 時,透過 notice.setLatestEventInfo 搭配 PendingIntent.getActivity,就能指定使用者點擊通知後要跳轉的目標頁面。此時頁面並不會立即跳轉,而是等到使用者真正點擊通知時才觸發。

應用示例二:簡訊發送回調

在 GSM 網路中發送簡訊時,SmsManager.sendTextMessage 方法接受兩個 PendingIntent 參數:sentIntent 在簡訊成功發出時,會把它內部描述的 Intent 廣播出去,否則產生錯誤碼並回呼;deliveryIntent 則是在訊息已成功傳遞給收信人後所進行的廣播。

PendingIntent 就是一個 Intent 的描述——我們把這個描述交給別的程式,它就能在後續的某個時間點,替我們執行安排好的操作。別的程式收到這個 PendingIntent,就等同獲得了「如同你本人一般執行該 Intent」的權利。理解這層設計,是掌握 Android 通知與背景任務調度的關鍵。

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