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

Android Notification 通知的基本寫法與常見設定

編輯:關於 Android 程式設計

狀態列通知是 App 與使用者溝通最直接的管道。以下是一個完整可運行的寫法,涵蓋圖示、提示文字、提醒音、震動與點擊跳轉。

public class MainActivity extends Activity {

    private NotificationManager ntfmngr;
    private static final int NOTIFY_MESSAGE = 1;

    @Override
    public void onCreate() {
        super.onCreate();
        ntfmngr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        setNotifyType(R.drawable.logo, "這是一則通知訊息", 3);
    }

    private void setNotifyType(int icon, String text, int num) {
        // 點擊通知後要開啟的 Activity
        Intent notifyIntent = new Intent().setClass(getApplicationContext(), MainActivity.class);
        notifyIntent.setAction(Constants.UPDATE_HOME_LIST);
        // 接收端可藉 action 判斷是哪一種訊息

        PendingIntent appIntent = PendingIntent.getActivity(this, 0, notifyIntent, 0);

        Notification myNotification = new Notification();
        myNotification.flags = Notification.FLAG_AUTO_CANCEL;   // 點擊後自動消失
        myNotification.icon = icon;

        // 自訂提示音:android.resource://[package]/raw/[name]
        Uri soundUri = Uri.parse("android.resource://com.sina.weibo/raw/notificationsound");
        myNotification.defaults = Notification.DEFAULT_SOUND;
        myNotification.sound = soundUri;

        if (num != -1) {
            myNotification.number = num;      // 狀態列上的數字
        }

        long[] vb = new long[] { 80, 80 };    // 震動節奏:震 80ms、停 80ms
        myNotification.vibrate = vb;

        myNotification.tickerText = text;     // 短暫滑過狀態列的文字
        myNotification.setLatestEventInfo(this, getString(R.string.app_name), text, appIntent);

        // NOTIFY_MESSAGE 是這則通知的 id,之後可用相同 id 取消或更新
        ntfmngr.notify(NOTIFY_MESSAGE, myNotification);
    }
}

震動需要權限

少了這一行,vibrate 設定不會有任何效果,也不會報錯:

<uses-permission android:name="android.permission.VIBRATE" />

取消通知

取消全部:

if (ntfmngr != null) {
    ntfmngr.cancelAll();
}

只取消指定的一則,用同一個 id:

ntfmngr.cancel(NOTIFY_MESSAGE);

關鍵觀念說明

  • id 就是通知的身分:以相同 id 再次呼叫 notify() 不會疊加出新通知,而是更新原通知——這正是實作「下載進度」的正確方式。要取消或更新都靠這組 id。
  • FLAG_AUTO_CANCEL:使用者點擊後通知自動消失。若省略,通知會一直留在下拉列表中,需另外呼叫 cancel()。
  • PendingIntent 的 requestCode 與 flags:多個通知若用相同 requestCode 且 Intent 內容相同,可能會共用同一個 PendingIntent。加上 FLAG_UPDATE_CURRENT 並讓 Intent 的 data 或 action 有所差異,是最穩妥的做法。
  • id 從 0 開始:id 為 0 完全合法,但有些舊版本在處理上有邊界問題,實務上建議從 1 起算。

重要提醒:這套 API 已經不能用

上面使用的 new Notification()、setLatestEventInfo()、sound、vibrate、tickerText 全都已在 Android 8.0(API 26)被移除或忽略。目前的正確做法是 NotificationCompat + NotificationChannel:

// 1. Android 8.0 起必須先建立 notification channel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel(
            "default", "一般通知", NotificationManager.IMPORTANCE_DEFAULT);
    ntfmngr.createNotificationChannel(channel);
}

// 2. 用 Builder 組裝
Notification notification = new NotificationCompat.Builder(this, "default")
        .setSmallIcon(R.drawable.logo)          // 必要,且必須是單色透明圖
        .setContentTitle(getString(R.string.app_name))
        .setContentText("這是一則通知訊息")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setAutoCancel(true)
        .setContentIntent(appIntent)
        .build();

ntfmngr.notify(NOTIFY_MESSAGE, notification);

新版的提醒音與震動由 channel 決定,不再逐則設定;setSmallIcon 是必填項,且系統只取圖形的 alpha 通道上色,直接使用彩色圖會得到一片白色方塊。若要在 Android 13 以上發出通知,還需先取得 POST_NOTIFICATIONS 執行期權限。

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