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

Android 建立 Notification 的正確寫法:告別已棄用的建構子

編輯:關於 Android 程式設計

在 Android 開發中,建立通知的方式已經有過一次重要變革。直接呼叫 Notification 的舊建構子,如今已不被建議使用:

// 舊寫法,已不建議使用
Notification notification = new Notification(
        R.drawable.ic_launcher,
        "This is ticker text",
        System.currentTimeMillis());

這種寫法的問題在於參數眾多、語意不明,順序寫錯也不會有編譯錯誤,而且無法清楚表達各欄位的用途。

改用 Notification.Builder

目前的標準做法是透過 Notification.Builder,以鏈式呼叫逐步設定各項屬性:

Notification notification = new Notification.Builder(this)
        .setContentTitle("This is title")     // 通知標題
        .setContentText("This is content")    // 通知內容
        .setSmallIcon(R.drawable.ic_launcher) // 狀態列小圖示
        .setTicker("This is ticker")          // 首次提示時的滾動文字
        .setContentIntent(pi)                 // 點擊後要啟動的 PendingIntent
        .build();

Builder 模式的優點很直接:每一行做一件事,程式碼可讀性大幅提升,新增或調整欄位時也不必擔心參數位置錯亂。

幾個實務提醒

  • setSmallIcon() 是必填項,缺少它通知不會正常顯示。
  • setContentIntent() 需要傳入 PendingIntent,這是使用者點擊通知後要執行的動作。
  • 若要向下相容舊版系統,建議改用 NotificationCompat.Builder(v7 或 AndroidX 支援庫),並搭配 NotificationManager.notify() 發出通知。

掌握 Builder 的鏈式寫法,是後續處理通知渠道(NotificationChannel)、進度條與自訂樣式等進階功能的基礎。

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