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

Android Notification 通知機制與 Builder 設定詳解

編輯:關於 Android 程式設計

Notification(通知)是一種具全域效果的通知:它出現在螢幕頂端,先以圖示形式存在,使用者向下滑動後才展開完整內容。

一、通知在不同裝置上的差異

Notification 是狀態列的通知控件,由於各家 ROM 對狀態列的改造程度不同,同一支 App 在不同機型上的外觀與行為可能有所差異。

二、通知的基本組成

  • Icon / Photo:大圖示。
  • Title / Name:標題。
  • Message:內容訊息。
  • Timestamp:通知時間,預設是系統發出的時間,可用 setWhen() 指定。
  • Secondary Icon:小圖示。

三、使用流程

狀態列通知主要涉及兩個類別:Notification 是通知資訊本體,對應通知欄的各種屬性;NotificationManager 是管理類別,負責發送與清除通知。

step1:取得 NotificationManager

NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

step2:建立 Builder

Notification.Builder builder = new Notification.Builder(this);

step3:設定標題、內容、圖示與點擊行為。

step4:呼叫 build() 取得 Notification 物件。

step5:呼叫 manager.notify() 發送通知;若要取消,則呼叫 manager.cancel()。

四、常用設定方法

  • setContentTitle(CharSequence):設定標題。
  • setContentText(CharSequence):設定內容。
  • setSubText(CharSequence):在內容下方加一小行文字。
  • setTicker(CharSequence):收到通知時頂部滾動顯示的文字。
  • setWhen(long):通知時間,通常填 System.currentTimeMillis()。
  • setSmallIcon(int):右下角小圖示,同時也是狀態列顯示的圖示。
  • setLargeIcon(Bitmap):左側大圖示。
  • setAutoCancel(boolean):點擊通知後是否自動取消(預設不取消)。
  • setDefaults(int):套用系統預設的提醒效果,可組合使用:DEFAULT_VIBRATE(震動)、DEFAULT_SOUND(鈴聲)、DEFAULT_LIGHTS(呼吸燈)、DEFAULT_ALL(全部)。

setVibrate(long[]):自訂震動節奏,例如

setVibrate(new long[] {0, 300, 500, 700});

代表延遲 0ms、震動 300ms、停 500ms、再震 700ms。

setLights(int argb, int onMs, int offMs):設定呼吸燈,參數依序為顏色、亮燈持續時間、熄滅時間。可用顏色依硬體而異,部分機型沒有三色燈;此外還需要把 flags 設為 Notification.FLAG_SHOW_LIGHTS 才會生效。

setSound(Uri):設定鈴聲,可用系統音或自訂音:

.setDefaults(Notification.DEFAULT_SOUND)                            // 系統預設鈴聲
.setSound(Uri.parse("file:///sdcard/xx/xx.mp3"))                   // 自訂鈴聲
.setSound(Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "5"))  // 多媒體庫內的鈴聲

setOngoing(boolean):設為 true 表示這是一個「進行中」的通知,通常用來表示使用者正在參與的後台工作(例如播放音樂),或正在等待系統資源的作業(例如檔案下載、資料同步、持續的網路連線)。

setProgress(int, int, boolean):帶進度條的通知,參數依序為最大值、目前進度、是否為不確定狀態。

確定的進度條:以 setProgress(max, progress, false) 設定,更新時重新發送通知並更新 progress,完成後呼叫 setProgress(0, 0, false) 移除進度條。不確定的進度條(無法得知精確進度時):呼叫 setProgress(0, 0, true),結束時改回 setProgress(0, 0, false) 並更新通知。

setContentIntent(PendingIntent):PendingIntent 與 Intent 略有不同,它可以設定執行次數,主要用於遠端服務通訊、鬧鐘、通知、啟動器與短信等場景。透過 PendingIntent 啟動 Activity 用 getActivity(Context, int, Intent, int),當然也可以啟動 Service 或 Broadcast。

第四個參數(flag)的意義:

  • FLAG_ONE_SHOT:此 PendingIntent 只能執行一次,之後自動取消。
  • FLAG_NO_CREATE:若描述的 PendingIntent 不存在就不建立,直接回傳 null。
  • FLAG_CANCEL_CURRENT:若已存在則先取消舊的再建新的,有助於保持資料為最新狀態,適合即時通訊場景。
  • FLAG_UPDATE_CURRENT:更新現有的 PendingIntent。
// 點擊後跳轉 Activity
Intent intent = new Intent(context, XXX.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
mBuilder.setContentIntent(pendingIntent);

setPriority(int):設定優先級,對應 Notification.PRIORITY_HIGH 等常數:

  • MAX:重要而緊急,時間上急迫或需立即處理。
  • HIGH:重要的訊息類通知,例如短信或聊天訊息。
  • DEFAULT:沒有特別優先級分類的通知。
  • LOW:可以通知但並不緊急的事件。
  • MIN:背景訊息(例如天氣、位置),最低優先級,僅在狀態列顯示圖示,需下拉才能看到內容。

五、基本實例

package com.example.test3;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener {

    private Button btn1;
    private Button btn2;

    private NotificationManager manager;
    private Notification notification;

    private static final int NOTIFYID_1 = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn1 = (Button) findViewById(R.id.btn1);
        btn2 = (Button) findViewById(R.id.btn2);
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);

        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn1: {
                // 點擊通知後要跳轉的頁面
                Intent intent = new Intent(MainActivity.this, OtherActivity.class);
                PendingIntent pit = PendingIntent.getActivity(
                        MainActivity.this, 0, intent, 0);

                Notification.Builder builder = new Notification.Builder(MainActivity.this);
                builder.setContentTitle("葉良辰")                    // 標題
                       .setContentText("我有一百種方法讓你呆不下去~")   // 內容
                       .setSubText("——記住我叫葉良辰")                // 內容下方小字
                       .setTicker("收到葉良辰發送過來的信息~")         // 狀態列提示文字
                       .setWhen(System.currentTimeMillis())          // 通知時間
                       .setSmallIcon(R.mipmap.ic_account)            // 小圖示
                       .setLargeIcon(BitmapFactory.decodeResource(
                               getResources(), R.mipmap.ic_launcher)) // 大圖示
                       .setDefaults(Notification.DEFAULT_LIGHTS
                                  | Notification.DEFAULT_VIBRATE)    // 預設燈光與震動
                       .setAutoCancel(true)                          // 點擊後取消
                       .setContentIntent(pit);

                notification = builder.build();
                manager.notify(NOTIFYID_1, notification);
                break;
            }
            case R.id.btn2: {
                manager.cancel(NOTIFYID_1);
                break;
            }
        }
    }
}

新版 Android 若要讓通知正常顯示,務必先建立 NotificationChannel 並在 Builder 中指定 channel id;Android 13 以上發送通知還需要 POST_NOTIFICATIONS 執行期權限。這些是沿用舊寫法時最常遇到的失敗原因。

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