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

Android PendingIntent 用法詳解:作用、示例與和 Intent 的區別

編輯:關於 Android 程式設計

PendingIntent 從字面看就是「等待的、未決定的 Intent」。要獲得一個 PendingIntent 對象,可使用其靜態方法 getActivity()、getBroadcast()、getService(),分別對應跳轉 Activity、發送廣播、啟動 Service 三種行為。

PendingIntent 是一種特殊的 Intent,兩者的主要區別在於:Intent 是立即執行的,而 PendingIntent 的執行並非立即——它實質上執行的是傳入的 Intent 操作,但這個操作往往需要滿足某些條件才會被觸發。它主要用於通知 Notification 的發送、短信 SmsManager 的發送以及警報器 AlarmManager 的執行等場景。

狀態欄通知示例

查看消息時,只需將狀態欄拖到屏幕下方即可。步驟為:獲取 NotificationManager、建立 Notification、為其設置參數(聲音、震動、燈光)、最後添加到通知管理器。發送代碼如下:

  NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); int icon = android.R.drawable.stat_notify_chat; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, null, when); 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); 

重點在於 setLatestEventInfo() 的最後一個參數——它是一個 PendingIntent。

PendingIntent 可以看作對 Intent 的包裝,它主要持有它所包裝的 Intent 以及當前 Application 的 Context。正因為 PendingIntent 中保存了應用 Context,它賦予了「帶着它的程序」一種執行 Intent 的能力:即便執行時原應用已不存在,也能通過其中的 Context 照樣執行 Intent。

短信系統示例

SmsManager 用於發送短信的方法:

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

  • 第一個參數:對方手機號碼。
  • 第二個參數:短信中心號碼,一般設置為空。
  • 第三個參數:短信內容。
  • 第四個參數 sentIntent:判斷短信「發送」動作是否成功(如無 SIM 卡或網絡中斷)。
  • 第五個參數 deliveryIntent:當短信送達收件人時觸發,強調「發送」後的結果。

也就是說,只有在「短信發送成功」和「對方收到此短信」時,才會分別激活 sentIntent 與 deliveryIntent,這相當於延遲執行了 Intent。

PendingIntent 的作用總結

顧名思義,它是延遲的 Intent,主要用於在某個事件完成後執行特定的 Action。由於它包含了 Intent 及 Context,即使原程序結束,PendingIntent 依然有效,可在其他程序中使用,常用於通知欄與短信發送系統。

PendingIntent 一般作為參數傳給某個實例,在該實例完成某操作後自動執行其上的 Action;也可以通過 send() 函數手動執行,並在其中設置 OnFinished 表示發送成功後的動作。

Intent 與 PendingIntent 的區別

  • Intent 是立即使用的,而 PendingIntent 可以等到事件發生後觸發,且可以 cancel。
  • Intent 在程序結束後即終止,而 PendingIntent 在程序結束後依然有效。
  • PendingIntent 自帶 Context,而 Intent 需要在某個 Context 內運行。
  • Intent 在原 task 中運行,PendingIntent 在新的 task 中運行。

補充:token 與 flag

當你把 PendingIntent 遞交給其他程序處理時,它仍擁有原程序的權限與身份,因此從系統提取時要格外小心。一個 PendingIntent 相當於系統中某個 token 的對象引用。如果你提取的 PendingIntent 與系統中已有的某個「等價」PendingIntent 相匹配,系統會直接返回同一 token 的對象,而非創建新的。此時可透過 FLAG_CANCEL_CURRENT 先取消舊的再獲取新的,或用 FLAG_UPDATE_CURRENT 讓新 Intent 更新舊 Intent 的 Extras 數據;也可以在原告程序中調用 cancel() 將其從系統移除。

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