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

Android 通知機制入門:打造你的第一則通知

編輯:關於 Android 程式設計

引言

通知的用途,是在有事件發生時,以便利的方式將訊息呈現給使用者,讓他們能在自己方便的時候再與通知互動。如果你想了解如何設計有效且時機得宜的通知,可以參考 Notifications design guide 課程。本文則聚焦於實作層面,教你如何打造一則通用的通知。

打造通知

本節的實作主要建立在 NotificationCompat.Builder 類別之上,它屬於支援庫的一部分。開發者應優先採用 NotificationCompat 及其子類別,特別是 NotificationCompat.Builder,如此才能相容於更廣泛的裝置版本。

建立通知建構器

建立通知時,你需要指定通知的使用者介面內容,以及它的點擊行為。一個 Builder 物件至少應包含以下要素:

一張小圖示,透過 setSmallIcon() 設定。 通知標題,透過 setContentTitle() 設定。 詳細文字,透過 setContentText() 設定。

舉例來說:

 NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("My notification") .setContentText("Hello World!");

定義通知的行為

建立通知時,應至少為它加上一個行為。這個行為會在使用者點擊時,將他們帶往一個 Activity,其中詳細呈現發生了什麼事,或讓使用者能採取進一步行動。在通知內部,行為由 PendingIntent 所包含的 Intent 指定,它可用來啟動 Activity。

PendingIntent 的建構方式,取決於你要啟動的 Activity 類型。當通知要啟動 Activity 時,開發者必須考量使用者期待的導覽體驗。在以下程式碼中,點擊通知會啟動一個新的 Activity,它承接了通知所引發的行為脈絡。在這種情況下,就不需要刻意建立回退堆疊。

 Intent resultIntent = new Intent(this, ResultActivity.class); ... // Because clicking the notification opens a new ("special") activity, there's // no need to create an artificial back stack. PendingIntent resultPendingIntent = PendingIntent.getActivity( this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT );

設定通知的點擊行為

要讓 PendingIntent 與手勢產生關聯,需呼叫 NotificationCompat.Builder 的對應方法。例如,若要啟動一個 Activity,只要呼叫 setContentIntent() 並傳入 PendingIntent 即可。

發布通知

發布通知需要執行以下步驟:

取得 NotificationManager 的實例。 呼叫 notify() 方法發布通知;呼叫時需指定通知的 ID,這個 ID 可供日後更新同一則通知時使用。 呼叫 build() 方法,它會回傳一個 Notification 物件。
 NotificationCompat.Builder mBuilder; ... // Sets an ID for the notification int mNotificationId = 001; // Gets an instance of the NotificationManager service NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // Builds the notification and issues it. mNotifyMgr.notify(mNotificationId, mBuilder.build());
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved