要将接收到的推送通知分组,类似Gmail,你可以使用NotificationChannel
来创建不同的通知组。以下是一个示例代码,演示了如何创建多个通知组并将推送通知分配给相应的组。
首先,你需要在onCreate()
方法中创建通知通道:
private void createNotificationChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// 创建第一个通知组
NotificationChannel channel1 = new NotificationChannel("channel1", "Channel 1", NotificationManager.IMPORTANCE_HIGH);
channel1.setDescription("This is Channel 1");
// 创建第二个通知组
NotificationChannel channel2 = new NotificationChannel("channel2", "Channel 2", NotificationManager.IMPORTANCE_DEFAULT);
channel2.setDescription("This is Channel 2");
// 获取通知管理器
NotificationManager manager = getSystemService(NotificationManager.class);
// 添加通知组到通知管理器
manager.createNotificationChannel(channel1);
manager.createNotificationChannel(channel2);
}
}
接下来,你可以在接收到推送通知时,为通知指定所属的通知组。例如,你可以使用通知组的ID(上述示例中为channel1
和channel2
)来指定通知属于哪个组:
private void sendNotification(String channelId, String title, String message) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, builder.build());
}
在你需要发送通知的地方,调用sendNotification()
方法,并传入相应的通知组ID、标题和消息内容。
这样,当你发送通知时,它们将根据指定的通知组进行分组显示,类似于Gmail中的邮件分组。