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

Android 通知(Notification)的建立全流程

編輯:關於 Android 程式設計

通知是應用與使用者溝通的重要橋樑。建立一則通知,大致包含四個環節:建立通知的 Builder、定義通知的行為、設定點擊事件,以及發出通知。以下逐一拆解。

補充:使用 NotificationCompat.Builder 需引入 support 套件。延伸閱讀可參考官方文件 Notifications API Guide、Intents and Intent Filters 以及 Notifications Design Guide。

一、建立通知的 Builder

建立 Notification 時,NotificationCompat.Builder 負責定義其 UI。Builder 至少應包含以下方法:

setSmallIcon()    設定圖示
setContentTitle() 設定標題
setContentText()  設定詳情文字
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!");

二、定義通知的行為

雖然 action 是可選的,但仍強烈建議為通知加上一個。它能讓使用者直接從通知欄跳轉到你的 Activity,查看觸發通知的事件並做相應操作。在通知內部,action 是透過一個含 Intent 的 PendingIntent 來啟動 Activity。

Intent resultIntent = new Intent(this, ResultActivity.class);
// 由於點擊通知會開啟一個全新的 Activity,
// 因此無需建立人為的回退堆疊
PendingIntent resultPendingIntent = PendingIntent.getActivity(
        this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

三、設定通知的點擊行為

以先前建立的 PendingIntent 關聯到手勢上,呼叫 Builder 的對應方法即可。例如以 setContentIntent() 加入 PendingIntent,讓使用者點擊時啟動某個 Activity:

mBuilder.setContentIntent(resultPendingIntent);

四、發出通知

發出通知需满足兩個條件:取得 NotificationManager 的實例,並使用 notify() 方法發出。呼叫 notify() 時需帶上一個特定的 id,日後可透過這個 id 來更新通知;最後呼叫 build() 取得包含說明的 Notification 物件。

int mNotificationId = 001;
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());

完整程式碼如下:

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

Intent resultIntent = new Intent(this, AActicity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
        this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);

int mNotificationId = 001;
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = mBuilder.build();
// notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR; // 可使通知常駐通知欄
mNotifyMgr.notify(mNotificationId, notification);

若想讓通知常駐通知欄不被清除,可加上 FLAG_ONGOING_EVENT 與 FLAG_NO_CLEAR 旗標。掌握這套流程,你就能輕鬆地在應用中送出功能完整的通知。

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