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

Android 通知欄(Notification)實作教學

編輯:關於 Android 程式設計

通知是 Android 應用與使用者溝通的重要管道。本文示範如何用 NotificationCompat.Builder 建立一則功能完整的通知,並逐一說明各項設定。

完整程式碼

package com.example.mynotification;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.Menu;

public class MainActivity extends Activity {

    /** 建立一個預設的 PendingIntent,供通知點擊使用 */
    public PendingIntent getDefalutIntent(int flags) {
        return PendingIntent.getActivity(this, 1, new Intent(), flags);
    }

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

        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);

        mBuilder.setContentTitle("測試標題")                    // 通知欄標題
                .setContentText("測試內容")                    // 通知欄內容
                .setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL))
                .setTicker("測試通知來啦")                      // 首次出現時的提示文字(含動畫)
                .setWhen(System.currentTimeMillis())          // 通知時間,一般用系統時間
                .setPriority(Notification.DEFAULT_ALL)        // 優先級
                .setOngoing(false)                            // true 表示「進行中」的通知
                .setDefaults(Notification.DEFAULT_VIBRATE)    // 加入震動(需 VIBRATE 權限)
                .setSmallIcon(R.drawable.ic_launcher);        // 狀態列小圖示(必填)

        Notification notification = mBuilder.build();

        // 設為 ongoing 事件,使用者滑掉時不會被清除
        notification.flags = Notification.FLAG_ONGOING_EVENT;
        // 點擊清除鈕時不移除
        notification.flags = Notification.FLAG_NO_CLEAR;

        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                      | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

        PendingIntent pendingIntent =
                PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
        mBuilder.setContentIntent(pendingIntent);

        mNotificationManager.notify(0, mBuilder.build());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

各項設定說明

setSmallIcon() —— 必填,缺了通知不會出現
這是新手最常遇到的「程式沒報錯但通知不出來」。系統要求必須有狀態列小圖示。另外從 Android 5.0 起,狀態列圖示會被系統強制渲染成單色剪影,因此請準備純白透明底的單色 PNG,直接拿彩色 App icon 會顯示成一塊白色方塊。

setContentIntent() —— 點擊通知後要做什麼
接受一個 PendingIntent。這是通知能「可操作」的關鍵:通知由系統 (NotificationManager) 顯示,而 PendingIntent 授權系統代為執行你的意圖。

setTicker() —— 首次滑入時的提示
在早期版本上會伴隨文字跑馬燈動畫。Android 4.1 之後這個動畫效果已大幅弱化,但仍可作無障礙 (accessibility) 讀出的依據。

setOngoing(true) —— 使用者無法滑掉
適合音樂播放、導航、通話、檔案傳輸這類「正在進行中」的通知。濫用會讓使用者困擾,請審慎使用。

setDefaults()
可組合 DEFAULT_SOUND(提示音)、DEFAULT_VIBRATE(震動)、DEFAULT_LIGHTS(呼吸燈)、DEFAULT_ALL。使用震動需要 android.permission.VIBRATE 權限。

notification.flags 的兩個常用值

  • FLAG_ONGOING_EVENT:標記為進行中事件
  • FLAG_NO_CLEAR:按下「清除全部」時保留這則通知

為什麼「點擊後還是不會消失」?

原作者在程式碼註解中記錄了一個困惑:明明設了 FLAG_AUTO_CANCEL,點擊後通知卻還在。

原因就在程式碼裡:你自己後面又把 flags 覆蓋掉了。

notification.flags = Notification.FLAG_ONGOING_EVENT;
notification.flags = Notification.FLAG_NO_CLEAR;   // 這行把前面全部蓋掉

flags 是位元遮罩(bitmask),正確的合併方式是用 bitwise OR:

notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.flags |= Notification.FLAG_NO_CLEAR;

但更根本的問題是:FLAG_NO_CLEAR 的語意正是「不要讓使用者清除我」,它與「點擊後自動消失」是互相衝突的需求。想要點擊後消失,正確做法不是設定 setAutoCancel(true),而是在 PendingIntent 觸發時呼叫 cancel():

// 在被打開的 Activity 的 onCreate 中
mNotificationManager.cancel(0);   // 0 是 notify 時用的 id

或者更進一步,改用 TaskStackBuilder 建立正確的返回堆疊,並在 Activity 中明確取消通知。

新版 Android 必須知道的變化

本文寫法在當時可用,但從 Android 5.0 一路演進到現在,通知系統有幾項重大變革:

1. 通知渠道(NotificationChannel)—— Android 8.0 起強制
不建立渠道就直接 notify(),通知完全不會顯示,也不會報錯。必須先:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel(
            "my_channel_id",
            "我的通知",
            NotificationManager.IMPORTANCE_DEFAULT);   // 重要性由使用者可調
    channel.setDescription("這是頻道的說明");
    mNotificationManager.createNotificationChannel(channel);
}
// Builder 必須帶入 channel id
NotificationCompat.Builder builder =
        new NotificationCompat.Builder(this, "my_channel_id");

渠道一旦建立,其重要性等級只能由使用者修改,程式無法再變更——這是刻意的設計,避免 App 反覆把使用者調低的等級拉回去。若要新增不同重要性的通知,必須建立新的 channel。

2. PendingIntent 必須指定 FLAG_IMMUTABLE 或 FLAG_MUTABLE
Android 12 起,PendingIntent 若不明確標示可變性會直接拋 IllegalArgumentException。純通知點擊用途應該用:

PendingIntent pi = PendingIntent.getActivity(
        this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

3. Android 13 需要 POST_NOTIFICATIONS 執行期權限
不申請並取得使用者同意,通知不會顯示。這是不可跳過的一步。

4. setPriority() 已無效
從 Android 8.0 起,優先級改由渠道的 importance 決定,setPriority() 在新版系統上不再有任何效果。

5. 新專案請用 NotificationCompat 的完整 Builder API

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_stat_notification)
        .setContentTitle("標題")
        .setContentText("內容")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setAutoCancel(true)                     // 點擊後自動取消(最簡單的做法)
        .setContentIntent(pendingIntent);

NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, builder.build());

setAutoCancel(true) 會讓系統在 PendingIntent 被觸發時自動 cancel 這則通知,正好解決原文遇到的困惑,比自己處理 flags 省事得多。

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