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(狀態列上的圖示)
· 一組標題與展開後的內文
· 一個 PendingIntent(點擊通知後要跳去哪裡)

其餘都是加分項:狀態列頂部的 ticker 提示文字、提示音、振動、指示燈閃爍等等。

通知的生命週期

發送

呼叫 NotificationManager.notify(int, Notification)。第一個參數是這則通知的唯一識別碼,第二個是通知物件本身。

更新

重新呼叫 setLatestEventInfo() 修改內容,再執行一次 notify() 並沿用同一個 ID 即可。實務上很常見:短信剛跳出還沒看,第二封又來了,這時更新原本的通知比再疊一則新通知友善得多。

刪除

用 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:

notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");

若偏好系統內建的鈴聲,可以這樣寫:

notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");

這裡有個容易踩到的細節:defaults 與 sound 同時存在時,sound 會失效,系統一律播放預設鈴聲。

另外,預設情況下提示音播完一次就停。若希望它持續響到使用者有所回應(例如下拉通知列),加上 FLAG_INSISTENT:

notification.flags |= notification.FLAG_INSISTENT;

震動的設定

使用系統預設震動:

notification.defaults |= Notification.DEFAULT_VIBRATE;

想要自訂節奏,就改用一個 Long 陣列:

long[] vibrate = {0, 100, 200, 300};
notification.vibrate = vibrate;

陣列的意義是「等待、震、停、震……」的時間序列(毫秒):第一個值是開始震動前的等待時間,第二個是第一次震動的持續時間,第三個是之後的間隔,以此類推,長度不限。這種寫法無法做到無限循環震動。同樣地,defaults 與 vibrate 並存時以 defaults 為準。

別忘了震動需要權限:

<uses-permission android:name="android.permission.VIBRATE"></uses-permission>

指示燈閃爍

使用預設燈光:

notification.defaults |= Notification.DEFAULT_LIGHTS;

自訂顏色與節奏:

notification.ledARGB = 0xff00ff00;
notification.ledOnMS = 300;
notification.ledOffMS = 1000;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;

其中 ledARGB 決定顏色,ledOnMS 是亮起的持續時間,ledOffMS 是熄滅時間。要注意燈光顏色能否呈現與硬體有關,並非每台機型都支援任意顏色。

幾個實用的 flags

// 提示音與震動持續循環,直到使用者回應
Notification.FLAG_INSISTENT;

// 通知被點擊後自動消失
Notification.FLAG_AUTO_CANCEL;

// 按下「清除」時不一起被清掉(某些即時通訊 App 的常駐通知就是這個效果)
Notification.FLAG_NO_CLEAR;

完整範例

下面的範例涵蓋了建立、更新、清除通知,以及自訂鈴聲、自訂震動與自訂通知版面。

主程式

package com.yfz;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Audio;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Lesson_10 extends Activity {
    private Button bt01, bt02, bt03, bt04, bt05, bt06, bt07;
    private NotificationManager nm;
    private PendingIntent pd;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lesson10);
        init();
    }

    private void init() {
        bt01 = (Button) findViewById(R.id.le10bt01);
        bt02 = (Button) findViewById(R.id.le10bt02);
        bt03 = (Button) findViewById(R.id.le10bt03);
        bt04 = (Button) findViewById(R.id.le10bt04);
        bt05 = (Button) findViewById(R.id.le10bt05);
        bt06 = (Button) findViewById(R.id.le10bt06);
        bt07 = (Button) findViewById(R.id.le10bt07);
        bt01.setOnClickListener(onclick);
        bt02.setOnClickListener(onclick);
        bt03.setOnClickListener(onclick);
        bt04.setOnClickListener(onclick);
        bt05.setOnClickListener(onclick);
        bt06.setOnClickListener(onclick);
        bt07.setOnClickListener(onclick);
        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Intent intent = new Intent(this, Lesson_10.class);
        pd = PendingIntent.getActivity(Lesson_10.this, 0, intent, 0);
    }

    OnClickListener onclick = new OnClickListener() {
        private int Notification_ID_BASE = 110;
        private Notification baseNF;
        private int Notification_ID_MEDIA = 119;
        private Notification mediaNF;

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.le10bt01:
                    baseNF = new Notification();
                    baseNF.icon = R.drawable.icon;
                    baseNF.tickerText = "You clicked BaseNF!";
                    baseNF.defaults |= Notification.DEFAULT_SOUND;
                    baseNF.defaults |= Notification.DEFAULT_VIBRATE;
                    baseNF.defaults |= Notification.DEFAULT_LIGHTS;
                    baseNF.flags |= Notification.FLAG_INSISTENT;
                    baseNF.flags |= Notification.FLAG_AUTO_CANCEL;
                    baseNF.flags |= Notification.FLAG_NO_CLEAR;
                    baseNF.setLatestEventInfo(Lesson_10.this, "Title01", "Content01", pd);
                    nm.notify(Notification_ID_BASE, baseNF);
                    break;
                case R.id.le10bt02:
                    // 沿用同一個 ID 即可原地更新內容
                    baseNF.setLatestEventInfo(Lesson_10.this, "Title02", "Content02", pd);
                    nm.notify(Notification_ID_BASE, baseNF);
                    break;
                case R.id.le10bt03:
                    nm.cancel(Notification_ID_BASE);
                    break;
                case R.id.le10bt04:
                    mediaNF = new Notification();
                    mediaNF.icon = R.drawable.icon;
                    mediaNF.tickerText = "You clicked MediaNF!";
                    mediaNF.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");
                    long[] vir = {0, 100, 200, 300};
                    mediaNF.vibrate = vir;
                    mediaNF.setLatestEventInfo(Lesson_10.this, "Title03", "Content03", pd);
                    nm.notify(Notification_ID_MEDIA, mediaNF);
                    break;
                case R.id.le10bt05:
                    nm.cancel(Notification_ID_MEDIA);
                    break;
                case R.id.le10bt06:
                    nm.cancelAll();
                    break;
                case R.id.le10bt07:
                    // 自訂展開後的版面,例如下載 App 時的進度條
                    Notification notification = new Notification();
                    notification.icon = R.drawable.icon;
                    notification.tickerText = "Custom!";
                    RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom);
                    contentView.setImageViewResource(R.id.image, R.drawable.icon);
                    contentView.setTextViewText(R.id.text, "Hello, this message is in a custom expanded view");
                    notification.contentView = contentView;
                    // 使用自訂版面時不必再呼叫 setLatestEventInfo(),但一定要指定 contentIntent
                    notification.contentIntent = pd;
                    nm.notify(3, notification);
                    break;
            }
        }
    };
}

主版面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <Button android:id="@+id/le10bt01" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="BaseNotification" />
    <Button android:id="@+id/le10bt02" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="UpdateBaseNotification" />
    <Button android:id="@+id/le10bt03" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="ClearBaseNotification" />
    <Button android:id="@+id/le10bt04" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="MediaNotification" />
    <Button android:id="@+id/le10bt05" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="ClearMediaNotification" />
    <Button android:id="@+id/le10bt06" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="ClearALL" />
    <Button android:id="@+id/le10bt07" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="CustomNotification" />
</LinearLayout>

自訂通知版面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="3dp">
    <ImageView android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_marginRight="10dp" />
    <TextView android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:textColor="#000" />
</LinearLayout>

補充一句:以上寫法屬於較早期的 Notification API 風格,在後續 Android 版本中 setLatestEventInfo() 與部分欄位已被 Builder 模式取代,實際專案請以目前 SDK 的建議做法為準,但觀念與參數設計思路是相通的。

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