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

Android 點滴之 PendingIntent 完全解析

編輯:關於 Android 程式設計

一、概念

PendingIntent 是一個「在滿足特定條件時才會被執行」的 Intent。相比起一般的 Intent,它最大的優勢在於自己攜帶了一個 Context,因此不必依附某個 Activity 才能存在。

兩者的核心差異是執行時機:Intent 是立即的,PendingIntent 是延後的。PendingIntent 最終執行的仍然是它所包裝的那個 Intent 的操作,但重點在於——這個操作何時執行,取決於外部條件的滿足,可能是使用者點了通知、鬧鐘時間到了、或短信成功送出了。

二、實質

可以把 PendingIntent 想成是對 Intent 的一層包裝。它主要持有兩樣東西:被包裝的 Intent,以及當前 Application 的 Context。

正因為它握有 Application 的 Context,PendingIntent 賦予了「其他程式」執行你的 Intent 的能力。這點非常關鍵:即使你的 App 進程此時已經被系統回收、不存在了,持有 PendingIntent 的那一方仍然能透過其中的 Context 把 Intent 跑起來。這也是為什麼鬧鐘鬧得響、通知點得開——你的 App 早就不在記憶體裡了。

三、常見使用場景

場景 1:定時鬧鐘

把 PendingIntent 交給 AlarmManager,讓系統在指定時間替你發送廣播:

PendingIntent pi = PendingIntent.getBroadcast(
        context, 1, new Intent(context, AutoTimeringBroadcast.class), 0);

AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// time 為目標時間的毫秒值
am.setRepeating(AlarmManager.RTC_WAKEUP, time, 1000 * 60 * 60 * 24, pi);

RTC_WAKEUP 表示會喚醒裝置;若不想喚醒,用 RTC。

場景 2:通知點擊後開啟 Activity

NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

Notification notification = new Notification(
        android.R.drawable.stat_notify_chat, null, System.currentTimeMillis());
notification.defaults = Notification.DEFAULT_SOUND;
notification.flags |= Notification.FLAG_AUTO_CANCEL;

Intent openintent = new Intent(this, OtherActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, openintent, 0);

notification.setLatestEventInfo(this, "標題", "我是內容", contentIntent);
mNotificationManager.notify(0, notification);

這裡的 PendingIntent 就是「點擊條件」的載體。使用者一點,系統就代你送出那個 Intent。

場景 3:短信發送後的回執

sendTextMessage(destinationAddress, scAddress, text, sentIntent, deliveryIntent);

五個參數的含義:

  1. destinationAddress:對方手機號碼。
  2. scAddress:短信中心號碼,一般留空。
  3. text:短信內容。
  4. sentIntent:判斷短信是否成功送出。若沒有 SIM 卡或網路中斷,會透過這個 Intent 得知。注意它關心的是「送出」這個動作。
  5. deliveryIntent:當短信送達收件人時觸發,關心的是「送出之後的結果」。

也就是說,只有在「送出成功」與「對方收到」這兩個條件成立時,對應的 PendingIntent 才會被啟動。本質上這就是一種延後執行。

四、三個容易踩到的細節

1. requestCode 與 PendingIntent 的「相等」判定

系統判斷兩個 PendingIntent 是否相同,看的是 requestCode + Intent 的 action、data、type、class、categories 這幾項,不包含 extras。這意味著如果你用相同的 requestCode 建立兩個只差 extras 的 PendingIntent,第二個會被視為重複。解法是改用不同的 requestCode,或在 flags 中加上 FLAG_UPDATE_CURRENT 讓新的 extras 覆蓋舊的。

2. 必須指定 FLAG_IMMUTABLE(Android 12 以上)

從 Android 12(API 31)開始,所有 PendingIntent 都必須明確宣告 FLAG_IMMUTABLE 或 FLAG_MUTABLE,否則會直接拋出 IllegalArgumentException。除非你真的需要讓接收方修改其中的內容,否則一律應該用 FLAG_IMMUTABLE——這是安全性上的要求,可避免 Intent 被填充竄改。

3. 別忘了 requestCode 用來避開衝突

像通知這種一個 App 可能同時發出好幾個的場景,如果每個都用 requestCode = 0,點下去會全部開同一個頁面。用通知 id 當 requestCode 是個實用的習慣。

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