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

實作 Android 的消息通知欄

編輯:關於 Android 開發

通知欄是 Android 應用與使用者互動的重要管道。本文說明如何使用 NotificationManager 與 Notification 兩個類別,在系統通知欄中送出通知。

背景知識:通知可由 Activity 或 Service 觸發,兩者的差別在於一個於前台觸發,一個於後台服務觸發。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 描述狀態列的圖示與提示文字,再以 PendingIntent 封裝點擊通知後要啟動的 Intent,最後呼叫 notify(id, notification) 送出。每則通知都有一個唯一 id,可用於後續更新或移除對應通知。

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