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

Android Notification 的建議建立方式

編輯:關於 Android 開發

Notification 的建立方式

在 Android 開發中,通知是常見功能。早期可以透過 new Notification 直接建立物件,但這種方式彈性較低,也不符合後續版本的設計方向。

不建議的寫法

Notification notification = new Notification(
    R.drawable.ic_launcher,
    "This is ticker text",
    System.currentTimeMillis()
);

這種寫法在新版 Android 中已不推薦,因為它難以設定完整內容、意圖與樣式。

建議使用 Notification.Builder

較好的方式是透過 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)
    .build();

使用 Builder 不僅語意清楚,也更容易擴充。後續若要加入 Notification Channel、Action 或自訂樣式,也能在相近的結構中完成。

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