Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

Android 狀態列通知與 PendingIntent 的用法解析

編輯:初階開發

PendingIntent 與 Intent 的差別

先看建立一個通知的基本寫法:

Notification n = new Notification(R.drawable.face_1, "Service啟動", System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
        new Intent(this, TServiceHolder.class), 0);
n.setLatestEventInfo(this, "任務標題", "任務內容", contentIntent);
nManager.notify(NOTIFICATION_ID, n);   // 在狀態列啟動通知

關鍵差異在於:通知被點擊時,需要交出一個「可以延後執行」的 Intent,而 PendingIntent 正是這樣一個包裝。

PendingIntent 到底是什麼

PendingIntent 是一個 Intent 的描述。我們把這個描述交給別的程式,對方就能在之後的某個時間點,依描述執行你安排好的操作。用官方文件說得更清楚:把 PendingIntent 交給另一個應用程式,等於授予它權限,讓它能以你的身分執行你指定的操作。

換句話說,PendingIntent 就代表了那個 Intent,只是執行的時間與執行者都不是你。

實例:GSM 網路下發送簡訊

String msg = "你好,美女";
String number = "135****6784";
SmsManager sms = SmsManager.getDefault();
PendingIntent pi = PendingIntent.getBroadcast(SmsActivity.this, 0, new Intent(...), 0);
sms.sendTextMessage(number, null, msg, pi, null);
Toast.makeText(SmsActivity.this, "發送成功", Toast.LENGTH_LONG).show();

在這個例子中,「別的程式」就是系統的簡訊傳送服務。簡訊送出後,它會依 PendingIntent 的描述把 Intent 廣播出來,讓你的程式得以掌握結果。

sendTextMessage 的參數說明

SmsManager.sendTextMessage(String destinationAddress, String scAddress,
        String text, PendingIntent sentIntent, PendingIntent deliveryIntent)
  1. sentIntent:簡訊發出時,若成功,這個 PendingIntent 內部描述的 Intent 會被廣播出來;若失敗,則產生錯誤碼並透過 android.app.PendingIntent.OnFinished 回呼。這個參數最好不要留空,否則存在資源浪費的潛在問題。
  2. deliveryIntent:當訊息已成功送達收件人時,才會觸發的 PendingIntent 廣播。

補充

查閱 PendingIntent 類別可以發現許多 send 系列方法,分別對應 getActivity、getBroadcast、getService 等差異——差別只在於被賦予的操作對象是 Activity、廣播還是 Service。理解這一點,通知、簡訊、鬧鐘、App Widget 等場景的用法就都能串起來了。

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