我不知道如何将两个或多个通知分组到一个,并显示“你有两条新消息”这样的消息。
答案 0 :(得分:31)
以下代码需要注意的步骤。
NotificationCompat.Builder:contains the UI specification and action information
NotificationCompat.Builder.build() :used to create notification (Which returns Notification object)
Notification.InboxStyle: used to group the notifications belongs to same ID
NotificationManager.notify():to issue the notification.
使用以下代码创建通知并对其进行分组。在按钮单击中包含该功能。
private final int NOTIFICATION_ID = 237;
private static int value = 0;
Notification.InboxStyle inboxStyle = new Notification.InboxStyle();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.push_notify_icon);
public void buttonClicked(View v)
{
value ++;
if(v.getId() == R.id.btnCreateNotify){
NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("Lanes");
builder.setContentText("Notification from Lanes"+value);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setLargeIcon(bitmap);
builder.setAutoCancel(true);
inboxStyle.setBigContentTitle("Enter Content Text");
inboxStyle.addLine("hi events "+value);
builder.setStyle(inboxStyle);
nManager.notify("App Name",NOTIFICATION_ID,builder.build());
}
}
对于单独的通知,请指定不同的NOTIFICATION_ID ..
答案 1 :(得分:1)
对于完整的逻辑,请考虑检查我的答案。我使用具有共享首选项和广播接收器的逻辑,因为我需要将每个用户消息分组为单个并且看到活动通知。仅通过针对api级别23你可以得到主动通知,它根本没有帮助我。所以我决定写一些轻微的逻辑。如果你愿意,请在这里查看。
答案 2 :(得分:0)
您需要创建通知,以便通过调用NotificationManager.notify(ID, notification)
使用通知ID进行更新。
需要创建以下步骤来更新通知:
NotificationCompat.Builder
对象取自android开发者docs的一个例子:
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 1;
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
numMessages = 0;
// Start of a loop that processes data and then notifies the user
...
mNotifyBuilder.setContentText(currentText).setNumber(++numMessages);
// Because the ID remains unchanged, the existing notification is updated.
mNotificationManager.notify(notifyID, mNotifyBuilder.build());
...
另请参阅堆叠通知上的Android文档 https://developer.android.com/training/wearables/notifications/stacks.html
答案 3 :(得分:0)
您可以使用 setGroup
方法并将所有groupId字符串作为参数传递,将所有通知堆叠到一个组中。
builer.setGroup(“组ID字符串”);
NotificationManager nManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("Lanes");
builder.setGroup("GROUP_ID_STRING");
builder.setContentText("Notification from Lanes"+value);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setLargeIcon(bitmap);
builder.setAutoCancel(true);
inboxStyle.setBigContentTitle("Enter Content Text");
inboxStyle.addLine("hi events "+value);
builder.setStyle(inboxStyle);
nManager.notify("App Name",NOTIFICATION_ID,builder.build());