Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 通知服務 Notification 的實作與取消

編輯:Android 開發實例

簡訊進來時手機會震動或響聲,狀態列同時出現帶圖示的提示——這就是通知功能。Android 為開發者提供了完整的通知介面,以下透過一個實際案例,說明如何發出與取消通知。

A. 取得系統服務

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

B. 建立 Notification

參數依序為圖示、提示文字、發出時間:

Notification notification = new Notification(R.drawable.n, "即興提示!", System.currentTimeMillis());

C. 建立 PendingIntent

通知被點擊時要執行什麼,由 PendingIntent 決定。它的特性是可以授權給系統在未來某個不確定的時間代為執行:

Intent intent = new Intent(this, NewActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);

D. 設定標題、內容與點擊行為

notification.setLatestEventInfo(this, "fengfly.com", "雨楓技術教程網!", contentIntent);

E. 發出通知

notificationManager.notify(1, notification);

F. 取消通知

notificationManager.cancel(1);

其中 1 是通知的 id:以相同 id 再次呼叫 notify() 會更新而非新增通知,cancel() 則依 id 撤銷對應的那一則。

實務提醒

新版 Android 有兩件事必須注意。第一,自 Android 8.0 起,通知一定要指定 NotificationChannel,否則通知根本不會顯示;建立頻道時需給定 id、名稱與重要度。第二,setLatestEventInfo() 已被棄用,應改用 Notification.Builder 串接式 API。另外若要搭配震動、鈴聲或 LED,可透過 notification.defaults 與 notification.flags 設定;下載類長時間任務則建議使用前台服務(foreground service)搭配常駐通知,並記得在使用者不再需要時主動取消,避免通知欄堆積。

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