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

Android PendingIntent 詳解:通知、短信與延遲 Intent

編輯:關於 Android 開發

Android PendingIntent 詳解:通知、短信與延遲 Intent

PendingIntent 可以理解為一個等待被觸發的 Intent。它與一般 Intent 最大的差異在於,PendingIntent 可以在未來某個時刻、某個條件滿足時,或由其他應用程式執行。它常用於通知欄、短信發送與鬧鐘等場景。

一、PendingIntent 與 Intent 的差異

  • Intent 通常是立即執行,PendingIntent 可以延遲執行。
  • PendingIntent 可以在原應用程式結束後仍然存在。
  • PendingIntent 自帶 Context,因此可以被其他應用程式安全地使用。
  • PendingIntent 可以取消、更新,也可以透過 flags 控制行為。

二、三種建立方式

根據要啟動的組件不同,可以選擇不同的靜態方法:

  • getActivity:用於啟動 Activity。
  • getBroadcast:用於發送 Broadcast。
  • getService:用於啟動 Service。

三、通知欄示例

在通知中,通常需要設置一個 PendingIntent,讓用戶點擊通知後可以跳轉到指定頁面。

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

Notification n = new Notification(icon, "通知", when);
n.defaults = Notification.DEFAULT_SOUND;
n.flags |= Notification.FLAG_AUTO_CANCEL;

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

n.setLatestEventInfo(this, "標題", "內容", pi);
nm.notify(0, n);

這裡的 PendingIntent 會在通知被點擊時觸發,讓系統執行 openintent 所描述的動作。

四、短信發送示例

SmsManager 的 sendTextMessage 方法也使用 PendingIntent。其中 sentIntent 表示短信是否發送成功,deliveryIntent 表示對方是否收到短信。

也就是說,PendingIntent 可以在特定事件完成後被觸發,這正是它與一般 Intent 最大的不同。

五、常用 flags

  • FLAG_CANCEL_CURRENT:如果已存在相同的 PendingIntent,先取消舊的,再建立新的。
  • FLAG_UPDATE_CURRENT:如果已存在相同的 PendingIntent,更新其中的 Intent 數據。

此外,也可以在合適的時機呼叫 PendingIntent.cancel,將其從系統中移除。

六、總結

PendingIntent 是 Android 中非常重要的延遲執行機制。它不僅能攜帶 Intent,還能攜帶 Context,因此可以在通知、短信、鬧鐘等場景中安全地觸發操作。理解它的執行時機與 flags 行為,才能避免重複通知、舊數據殘留與取消失敗等問題。

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