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

Android 訊息通知的兩種玩法:Toast 與 NotificationManager 實作對照

編輯:Android 開發實例

Android 支援 Toast 與 NotificationManager 兩種通知方式。前者相當於一個會自動關閉的對話框,適合短暫的提示;後者則是在狀態列上留下一條訊息,適合需要使用者稍後回頭處理的事件。兩者都可以隨時取消。

Toast

Toast 是一個承載簡短訊息的檢視,Toast 類別負責建立與顯示它。用法極為簡單:

Toast.makeText(this, "Service destroyed…", Toast.LENGTH_LONG).show();

顯示時長只有兩種選擇:LENGTH_SHORT 與 LENGTH_LONG,無法自訂秒數。另外,Toast 是建立在一個背景執行緒的訊息佇列上,因此即便你的 Activity 已經不在前景,它一樣能顯示——這也是它特別適合在 Service 中回報狀態的原因。

NotificationManager

NotificationManager 負責通知使用者事件的發生,共提供三個公開方法:

1. cancel(int id):取消先前顯示的某一個通知。若它是短暫通知,會嘗試隱藏;若是持久通知,則從狀態列移除。

2. cancelAll():取消先前顯示的所有通知。

3. notify(int id, Notification notification):把通知持久地發送到狀態列上。

// 初始化 NotificationManager
NotificationManager nm =
    (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

Notification 代表著一則通知本身,可設定的屬性如下:

· audioStreamType:聲音響起時所用的音訊流類型
· contentIntent:點擊通知項目時執行的 Intent
· contentView:通知顯示在狀態列時同時呈現的自訂檢視
· defaults:指定哪些值要採用預設
· deleteIntent:使用者清除通知時執行的 Intent
· icon:狀態列所用的圖示
· iconLevel:狀態列圖示若有多個級別,在此設定
· ledARGB:LED 燈的顏色
· ledOffMS:LED 熄滅時的閃光時間(毫秒)
· ledOnMS:LED 亮起時的閃光時間(毫秒)
· number:這則通知代表的事件數量
· sound:通知音效
· tickerText:通知顯示在狀態列時所顯示的訊息
· vibrate:震動模式
· when:通知的時間戳記

Notification 的公開方法:

describeContents():描述這個 Parcelable 封送表示中包含的特殊物件種類。

setLatestEventInfo(Context context, CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent):設定 Notification 在狀態列上的各項參數。

writeToParcel(Parcel parcel, int flags):把 notification 攤平寫入 parcel。

toString():回傳字串表示。

將 Notification 發送到狀態列

Notification notification = new Notification(
        R.drawable.icon, "Service started", System.currentTimeMillis());

PendingIntent contentIntent = PendingIntent.getActivity(
        this, 0, new Intent(this, Main.class), 0);

// 必須設定這個,否則會拋出例外
notification.setLatestEventInfo(this, "Test Service",
        "Service started", contentIntent);

nm.notify(R.string.hello, notification);

這段程式碼示範了三個要素:建立 Notification 時傳入圖示、ticker 文字與時間戳;用 PendingIntent.getActivity 包裝一個「點擊後要前往哪裡」的意圖;最後透過 setLatestEventInfo 把標題與內容綁上去。

PendingIntent 是這裡最需要理解的概念。它並不是當下的 Intent,而是一個「授權書」——你把未來某個時刻要執行的操作交給系統保管,等使用者真的點了通知,系統才代你執行。這也是為什麼它能安全地跨應用、跨程序觸發你自己的 Activity。

取消通知

nm.cancel(R.string.hello);

實務上還有一個常見做法:設定 notification.flags = Notification.FLAG_AUTO_CANCEL。加上這個旗標後,使用者一旦點擊通知,系統會自動把它從狀態列移除,省下你自己寫取消邏輯的功夫。

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