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

Android Notification 通知用法總整理

編輯:關於 Android 程式設計

手機來了短信而我還沒點開時,狀態列上方會出現一個小圖示提示——這就是 Notification。本文把不同 Android 版本的通知寫法一次整理清楚。

主要程式碼

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) {
        // 通知管理器是系統 Service
        NotificationManager manager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        switch (view.getId()) {

            // 舊式寫法(相容 2.x,但已被棄用)
            case R.id.btn1:
                // PendingIntent 與 Intent 類似,但延後執行,
                // 適合用在「點通知才啟動」的場景
                PendingIntent pendingIntent =
                        PendingIntent.getActivity(this, 0,
                                new Intent(this, MainActivity.class), 0);

                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;
                // 點擊後自動清除
                notify1.flags |= Notification.FLAG_AUTO_CANCEL;

                manager.notify(NOTIFICATION_FLAG, notify1);
                break;

            // 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;

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

兩個常見技巧

讓通知常駐在「正在執行」區:設定 Notification.flags = Notification.FLAG_ONGOING_EVENT 即可,這正是音樂播放器那類應用的做法。

自訂常駐通知的版面:建立 RemoteViews 指定給 contentView,再把 PendingIntent 指定給 contentIntent:

PendingIntent contentIntent = PendingIntent.getActivity(
        arg0.getContext(), R.string.app_name, i,
        PendingIntent.FLAG_UPDATE_CURRENT);

RemoteViews rv = new RemoteViews(Main.this.getPackageName(),
        R.layout.notification_view);
rv.setImageViewResource(R.id.image, R.drawable.chat);
rv.setTextViewText(R.id.text, "Hello, there, I'm john.");

n.contentView = rv;
n.contentIntent = contentIntent;
nm.notify(R.string.app_name, n);

關鍵注意事項:一旦使用了 contentView,就不要再呼叫 setLatestEventInfo。兩者會互相覆蓋——誰寫在後面,畫面就顯示誰的效果。所以無論你想用哪種方式,請確保最後只有一行程式在設定它,先前的設定完全是多餘的。

最後提醒:Android 8.0(API 26)之後,所有通知都必須指定通知渠道(NotificationChannel),否則通知根本不會顯示;同時 setLatestEventInfo 已被移除,請一律改用 Notification.Builder 的串接寫法。

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