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

Android 實作:推送到通知狀態列

編輯:Android 開發實例

基礎觀念

通知可以從 Activity 或 Service 兩處發出,差別在於前者屬於前台觸發,後者則是背景服務觸發。若希望在 App 沒有開著時也能收到通知,就得靠 Service。

無論從哪裡發出,都離不開兩個類別:NotificationManager 與 Notification。NotificationManager 透過 getSystemService 取得,再呼叫 notify 方法把訊息送進系統的通知列。

程式碼

// ===== 通知狀態列 =====

// 取得 NotificationManager
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(ns);

// 通知列上方滾動顯示的內容
int icon = R.drawable.icon;
CharSequence tickerText = "我的通知欄標題";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);

// 下拉通知欄之後要顯示的詳細內容
Context context = getApplicationContext();
CharSequence contentTitle = "我的通知欄展開標題";
CharSequence contentText = "我的通知欄展開詳細內容";
Intent notificationIntent = new Intent(this, BootStartDemo.class);
PendingIntent contentIntent =
        PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

// 送出通知
mNotificationManager.notify(1, notification);

各欄位在說什麼

Notification 建構子需要三個參數:icon 是狀態列上的小圖示,tickerText 是通知送達瞬間會在狀態列滾動顯示的文字,when 則是時間戳記,系統會拿它來排序通知。

setLatestEventInfo 決定的是「使用者把通知列拉下來之後看到的樣子」:標題、副標題,以及點下去要前往的目標。

這裡有個關鍵是 PendingIntent。它不能直接放 Intent,因為通知是由系統代為觸發的,必須先包裝成 PendingIntent,把「要做什麼」授權給系統,等使用者點擊時代為執行。

最後 notify(1, notification) 的第一個參數是通知 ID。同一個 ID 重複發送會覆蓋舊通知而非新增一筆,這是實作「更新進度」類通知時常用的技巧。

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