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

Android 通知使用指南:Notification 基本實作

編輯:關於 Android 開發

Android 通知使用指南:Notification 基本實作

通知是 Android 應用與使用者互動的重要方式,常用於提示訊息、背景任務狀態或新內容抵達。本文以最基礎的寫法說明如何建立並發送一則通知。

版面準備

在 activity_main.xml 中建立一個按鈕,id 設為 send_notice,文字可設為 Send notice,用來觸發通知。

程式碼重點

MainActivity 先取得 NotificationManager,再建立 Notification 物件,設定通知圖示、提示文字、標題與內容,最後呼叫 notify 發送。

NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, "This is ticker text", System.currentTimeMillis());
notification.setLatestEventInfo(this, "This is content title", "This is content text", null);
manager.notify(1, notification);

此寫法屬於較舊的通知 API,適合理解基本概念;若為新專案,建議優先使用 NotificationCompat 與 NotificationChannel,以相容新版 Android 系統。

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