當通知訊息很多時,通知欄的位置就會非常長,甚至影響使用者要看其他APP通知的方便性
所以有個Group的功能,能將同分類的通知全部整合在一個群組通知裡,如以下官方文件的圖:

1.首先,以下是原本的單筆通知,我們在Builder中加上setGroup的參數進去:
Notification newMessageNotification = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.icon_bell)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)//點擊後通知自動關閉
.setWhen(time)//設定顯示時間
.setSound(defaultSoundUri)//自訂音效
.setContentIntent(pendingIntent)//點擊後要前往的畫面
.setGroup("FCM")//----增加此行----指定群組
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_DEFAULT)
.build();
//將通知顯示出來
notificationManager.notify(notifyIdIndex /* ID of notification */, newMessageNotification);
2.增加群組摘要(GroupSummary):
Notification summaryNotification = new NotificationCompat.Builder(this, channelId)
.setContentTitle(messageTitle)
//set content text to support devices running API level < 24
//舊裝置可能不支援收折後的樣式,所以自己訂一個子內容替代顯示,例如:您有N則新訊息
.setContentText(messageTitle)
.setSmallIcon(R.mipmap.icon_bell)
//build summary info into InboxStyle template
// .setStyle(new NotificationCompat.InboxStyle()
// .addLine("Alex Faarborg Check this out")
// .addLine("Jeff Chang Launch Party")
// .setBigContentTitle("2 new messages")
// .setSummaryText("janedoe@example.com"))
//specify which group this notification belongs to
.setAutoCancel(true)
.setGroup("FCM")//指定要套用此摘要的群組
//set this notification as the summary for the group
.setGroupSummary(true)//此通知是一個GroupSummary
.setContentIntent(pendingIntent)//點擊整個群組(沒有展開)要去的地方
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//最後,套用此summaryNotification
notificationManager.notify(1, summaryNotification);
這樣只要在同一個群組(FCM)裡的通知,就會自己收疊起來了,是不是很方便呢~
-END-
發佈留言