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

Android 狀態欄通知詳解:Notification 與 NotificationManager

編輯:關於 Android 程式設計

在 Android 中發送一條狀態欄通知其實很方便。本文將帶你了解通知的發送方式,以及究竟有哪些參數可以自定義。

發送通知離不開兩個核心類:NotificationManager 是通知的管理者,負責發通知、清通知等操作,它是一個系統 Service,需通過 getSystemService 獲取:

NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

Notification 則是具體的通知對象,可以設置圖標、文字、提示音、振動等屬性。

一條通知的基本要素包括:一個圖標(icon)、標題與內容(title 和 expanded message),以及一個 PendingIntent(用於點擊通知後的頁面跳轉)。可選的還包括狀態欄頂部的提示文字(ticker)、提示音、振動和燈光等。

通知的基本操作

發送通知調用 nm.notify(int id, Notification n),第一個參數是唯一標識,第二個是通知對象。更新通知時,重新調用 setLatestEventInfo 修改內容,再 notify 一次即可。刪除通知則用 nm.cancel(int id),若要清空全部通知則用 cancelAll()。

通知的各項設置

先來看最基礎的構建:

baseNF = new Notification();
baseNF.icon = R.drawable.icon;              // 狀態欄圖標
baseNF.tickerText = "You clicked BaseNF!";  // 頂部提示文字
baseNF.defaults = Notification.DEFAULT_SOUND; // 默認提示音
baseNF.setLatestEventInfo(Lesson_10.this, "Title01", "Content01", pd);
nm.notify(Notification_ID_BASE, baseNF);

添加聲音

使用默認聲音只需 baseNF.defaults = Notification.DEFAULT_SOUND;。若想自定義,則用 sound 屬性指向自己的音頻文件或系統鈴聲。注意:若 defaults 與 sound 同時出現,sound 會失效。默認情況下聲音只播放一遍,若希望循環播放直到用戶響應,需加上 FLAG_INSISTENT 標誌。

添加振動

默認振動用 notification.defaults |= Notification.DEFAULT_VIBRATE;;自定義振動則通過一個 Long 數組描述節奏,第一個值是開始前的等待時間,後面交替表示振動與停頓的時長。使用振動記得在清單中申請 android.permission.VIBRATE 權限。

添加閃光

通過 ledARGB(顏色)、ledOnMS(亮時長)、ledOffMS(暗時長)三個屬性,再配合 FLAG_SHOW_LIGHTS 標誌,即可實現呼吸燈效果。注意燈光顏色依設備而異,並非所有顏色都能生效。

其他常用標誌

FLAG_INSISTENT 讓聲音振動無限循環直到用戶響應;FLAG_AUTO_CANCEL 讓通知在被點擊後自動消失;FLAG_NO_CLEAR 則讓通知無法被「清除」按鈕清掉(QQ 的常駐通知就用到了這個特性)。

完整示例

下面通過一組按鈕演示通知的發送、更新、清除、自定義聲音振動以及自定義下拉視圖:

public class Lesson_10 extends Activity {
    private NotificationManager nm;
    private PendingIntent pd;
    private int Notification_ID_BASE = 110;
    private Notification baseNF;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lesson10);
        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Intent intent = new Intent(this, Lesson_10.class);
        pd = PendingIntent.getActivity(Lesson_10.this, 0, intent, 0);
        // 各按鈕的點擊邏輯省略
    }
}

如果需要更豐富的下拉展示(例如下載進度條),可以通過 RemoteViews 自定義通知的 contentView。此時不再需要調用 setLatestEventInfo,但必須自行指定 contentIntent:

Notification notification = new Notification();
notification.icon = R.drawable.icon;
notification.tickerText = "Custom!";
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom);
contentView.setTextViewText(R.id.text, "Hello, this is a custom view");
notification.contentView = contentView;
notification.contentIntent = pd;
nm.notify(3, notification);

掌握以上要點,你就能靈活地為應用加上恰到好處的通知提醒了。

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