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

Android Notification 通知實作大全:三種版本寫法與自訂版面

編輯:關於 Android 程式設計

手機收到簡訊時,即便沒有點開,最上方狀態列也會出現一個小圖示提示——這就是 Notification 的效果。本文整理三種不同 API 時期的通知建立方式,並示範自訂通知版面與清除通知的做法。

由於 Android 版本演進快速,Notification 的 API 經歷過多次更迭,有些寫法已被標記為不建議使用。以下範例刻意保留舊寫法,方便維護老專案時對照。

先取得通知管理器

無論哪一種寫法,第一步都是從系統服務中取得 NotificationManager,它是所有通知發送的入口。

核心程式碼

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 是一個系統 Service
        NotificationManager manager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        switch (view.getId()) {

            // 寫法一:直接 new Notification(),已被標記為不建議,但相容性最好
            case R.id.btn1:
                PendingIntent pendingIntent =
                        PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
                Notification notify1 = new Notification();
                notify1.icon = R.drawable.message;
                notify1.tickerText = "您有新短訊息,請注意查收!";
                notify1.when = System.currentTimeMillis();
                notify1.setLatestEventInfo(this, "Notification Title",
                        "This is the notification message", pendingIntent);
                notify1.number = 1;
                // 點擊後自動清除
                notify1.flags |= Notification.FLAG_AUTO_CANCEL;
                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("您有新短訊息,請注意查收!")
                        .setContentTitle("Notification Title")
                        .setContentText("This is the notification message")
                        .setContentIntent(pendingIntent2)
                        .setNumber(1)
                        .getNotification();   // API 11 用 getNotification()
                notify2.flags |= Notification.FLAG_AUTO_CANCEL;
                manager.notify(NOTIFICATION_FLAG, notify2);
                break;

            // 寫法三: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("您有新短訊息,請注意查收!")
                        .setContentTitle("Notification Title")
                        .setContentText("This is the notification message")
                        .setContentIntent(pendingIntent3)
                        .setNumber(1)
                        .build();             // build() 自 API 16 起提供
                notify3.flags |= Notification.FLAG_AUTO_CANCEL;
                manager.notify(NOTIFICATION_FLAG, notify3);
                break;

            // 寫法四:RemoteViews 自訂版面
            case R.id.btn4:
                Notification myNotify = new Notification();
                myNotify.icon = R.drawable.message;
                myNotify.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 world!");
                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:
                manager.cancel(NOTIFICATION_FLAG);
                // 若要一次清掉全部:manager.cancelAll();
                break;
        }
    }
}

PendingIntent 為什麼是必要的

通知並不是立刻被點擊的,使用者可能幾小時後才下拉狀態列。因此不能直接傳入 Intent,而要用 PendingIntent 把「未來某個時刻要執行的操作」包裝起來,交由系統代為觸發。

主版面 activity_main.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <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="預設通知(API 11 之後)" />
    <Button android:id="@+id/btn3" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="notificationMethod" android:text="預設通知(API 16 之後)" />
    <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>

實務提醒:FLAG_AUTO_CANCEL 讓通知在使用者點擊後自動消失,FLAG_NO_CLEAR 則相反,需要自行呼叫 cancel。另外,同一個 notify id 會覆蓋前一則通知,若要並存多則訊息,請給不同的 id。

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