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

Android Notification 用法總整理:四種建立方式與版本演進

編輯:Android 開發實例

手機來了簡訊而你沒點開,狀態欄上方會留一個小圖示提醒你——這就是 Notification。想在自己的應用裡做類似的事,就得把 Notification 這套 API 摸清楚。

麻煩的是 Android 的 Notification 經過多次改版,網路上抄來抄去的寫法有些早已被棄用。下面用同一個 Demo 實作四種建立方式,並標明各自適用的 API 等級。

一、核心觀念

無論哪一種寫法,流程都是三步:取得 NotificationManager → 建立 Notification → 呼叫 notify()。

其中 NotificationManager 是系統服務,用 getSystemService(Context.NOTIFICATION_SERVICE) 取得。而 PendingIntent 則是個容易卡住初學者的概念——它和 Intent 很像,但重點在「不是現在就執行」。使用者點擊通知才會觸發它,系統需要一個「授權票券」在未來那個時間點代 your app 啟動某個 Activity,這就是 PendingIntent 存在的理由。

二、主要程式碼

package net.loonggg.notification;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RemoteViews;

public class MainActivity extends Activity {
    private static final int NOTIFICATION_FLAG = 1;

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

    public void notificationMethod(View view) {
        // 取得系統的通知管理器
        NotificationManager manager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        switch (view.getId()) {

            // 寫法一:預設通知(舊式寫法,已被棄用但相容性最好)
            case R.id.btn1:
                PendingIntent pendingIntent = PendingIntent.getActivity(
                        this, 0, new Intent(this, MainActivity.class), 0);

                // Notification notify1 = new Notification(R.drawable.message,
                //         "TickerText:" + "您有新短消息,請注意查收!", System.currentTimeMillis());
                Notification notify1 = new Notification();
                notify1.icon = R.drawable.message;
                notify1.tickerText = "TickerText:您有新短消息,請注意查收!";
                notify1.when = System.currentTimeMillis();
                notify1.setLatestEventInfo(this, "Notification Title",
                        "This is the notification message", pendingIntent);
                notify1.number = 1;
                // FLAG_AUTO_CANCEL:使用者點擊後通知自動清除
                notify1.flags |= Notification.FLAG_AUTO_CANCEL;

                // 透過管理器發出通知。id 不同則每次都會新增一則
                manager.notify(NOTIFICATION_FLAG, notify1);
                break;

            // 寫法二:Notification.Builder(API 11 起可用)
            case R.id.btn2:
                PendingIntent pendingIntent2 = PendingIntent.getActivity(
                        this, 0, new Intent(this, MainActivity.class), 0);

                Notification notify2 = new Notification.Builder(this)
                        .setSmallIcon(R.drawable.message) // 狀態欄小圖,建議 24x24
                        .setTicker("TickerText:" + "您有新短消息,請注意查收!")
                        .setContentTitle("Notification Title")
                        .setContentText("This is the notification message")
                        .setContentIntent(pendingIntent2)
                        .setNumber(1)
                        .getNotification(); // API 16 起可用 build() 取代

                notify2.flags |= Notification.FLAG_AUTO_CANCEL;
                manager.notify(NOTIFICATION_FLAG, notify2);
                break;

            // 寫法三:Notification.Builder + build()(API 16 起)
            case R.id.btn3:
                PendingIntent pendingIntent3 = PendingIntent.getActivity(
                        this, 0, new Intent(this, MainActivity.class), 0);

                Notification notify3 = new Notification.Builder(this)
                        .setSmallIcon(R.drawable.message)
                        .setTicker("TickerText:" + "您有新短消息,請注意查收!")
                        .setContentTitle("Notification Title")
                        .setContentText("This is the notification message")
                        .setContentIntent(pendingIntent3)
                        .setNumber(1)
                        .build();

                notify3.flags |= Notification.FLAG_AUTO_CANCEL;
                manager.notify(NOTIFICATION_FLAG, notify3);
                break;

            // 寫法四:自訂版面
            case R.id.btn4:
                Notification myNotify = new Notification();
                myNotify.icon = R.drawable.message;
                myNotify.tickerText = "TickerText:您有新短消息,請注意查收!";
                myNotify.when = System.currentTimeMillis();
                myNotify.flags = Notification.FLAG_NO_CLEAR; // 不允許自動清除

                RemoteViews rv = new RemoteViews(getPackageName(), R.layout.my_notification);
                rv.setTextViewText(R.id.text_content, "hello wrold!");
                myNotify.contentView = rv;

                Intent intent = new Intent(Intent.ACTION_MAIN);
                PendingIntent contentIntent = PendingIntent.getActivity(this, 1, intent, 1);
                myNotify.contentIntent = contentIntent;

                manager.notify(NOTIFICATION_FLAG, myNotify);
                break;

            case R.id.btn5:
                // 清除 id 為 NOTIFICATION_FLAG 的通知
                manager.cancel(NOTIFICATION_FLAG);
                // 清除所有通知
                // manager.cancelAll();
                break;

            default:
                break;
        }
    }
}

三、主版面檔

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/btn1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="notificationMethod"
        android:text="預設通知(已被棄用,但通用)" />
    <Button
        android:id="@+id/btn2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="notificationMethod"
        android:text="預設通知(API11 之後可用)" />
    <Button
        android:id="@+id/btn3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="notificationMethod"
        android:text="預設通知(API16 之後可用)" />
    <Button
        android:id="@+id/btn4"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="notificationMethod"
        android:text="自定義通知" />
    <Button
        android:id="@+id/btn5"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="notificationMethod"
        android:text="清除通知" />
</LinearLayout>

四、自訂通知的版面檔

my_notification.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#ffffff"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/text_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp" />
</LinearLayout>

五、四種寫法的定位與現況

寫法一(setLatestEventInfo)在 API 23 已被移除,現在編譯不會過。留著是為了理解演進脈絡——它說明瞭通知的最小必要元素是什麼:icon、tickerText、when、contentIntent。

寫法二、三差別只在 getNotification() 與 build(),而這兩個方法本身也已進入棄用階段。目前的正確做法是全程使用 Notification.Builder 的 build(),並額外加上三件事:

  • 通知管道(NotificationChannel):API 26 起強制要求,必須先建立 channel 再發通知,否則通知完全不會顯示。
  • POST_NOTIFICATIONS 權限:API 33 起通知屬於執行時權限,需向使用者詢問同意。
  • 一律設定小圖示:setSmallIcon 在新版系統是必填,缺少會導致通知靜默失敗。

寫法四值得單獨說明的是 RemoteViews:它並不是普通的 View,而是一個「跨行程的版面描述」。系統行程要畫你的通知,所以只能傳遞受限的操作集合(設定文字、圖片等),不能塞自訂 View 進去。這也是自訂通知版面能用的控制項與屬性都比一般版面少的根本原因。新版 Android 對自訂通知的面板也有尺寸限制,過度客製化的版面會被系統裁切。

最後一個實務建議:notify() 的第一個參數(id)決定通知的身分。同一個 id 重複呼叫會更新而非新增,這在實作「下載進度」這類需要持續更新單一通知的場景非常有用;反之若每次都傳不同 id,使用者就會被一堆通知洗版。

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