1. 程式人生 > >Android訊息推送(廣播機制)+通知

Android訊息推送(廣播機制)+通知

Android廣播機制使用了觀察著模式;

(1) 通知

1) 獲取狀態通知欄管理

NotificationManager 是一個系統Service,所以必須通過getSystemService(NOTIFICATION_SERVICE)方法來獲取。

notificationManager=(NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);

2) 例項化通知欄構造器NotificationCompat.Builder

Notification.Builder notificationBuilder = new

Notification.Builder($.getContext())
        .setSmallIcon(R.drawable.notification_app_icon) // 設定狀態列中的小圖片,尺寸一般建議在24×24,這個圖片同樣也是在下拉狀態列中所顯示,如果在那裡需要更換更大的圖片,可以使用setLargeIcon(Bitmap.setPriority(Notification.PRIORITY_MAX)
        .setTicker(message)// 設定在status.setContentTitle(title)// 設定在下拉status.setContentText($
.util.strCut(message, 100))
        .setNumber(1); // TextView的右方顯示的數字,可放大圖片看,在最右側。這個number同時也起到一個序列號的左右,如果多個觸發多個通知(同一ID),可以指定顯示哪一個。

3) 設定PendingIntent

Intent intent = new Intent($.getContext(), LaunchActivity.class);
intent.putExtra(LaunchActivity.BUNDLE_EXTRA_NOTIFICATION, bundle);
PendingIntent pendingIntent2 = PendingIntent.getActivity

($.getContext(), 0,
        intent, PendingIntent.FLAG_CANCEL_CURRENT);
notificationBuilder.setContentIntent(pendingIntent2);

這裡PendingIntent表示的是就是啟動APP,而FLAG_CANCEL_CURRENT 表示相應的PendingIntent已經存在,則取消前者,然後建立新的PendingIntent

4) 設定鈴聲和震動執行一次

Notification notification =builder.build();

notification.flags =Notification.FLAG_ONLY_ALERT_ONCE;

這裡Notification.FLAG_ONLY_ALERT_ONCE就是表示的鈴聲和震動只執行一次。