处理多个GCM通知/堆叠通知

9
我刚刚在我的Android应用中实现了GCM和通知功能,这是从基于Apache/PHP的Web服务器转移过来的。通知已经可以正常工作了,但是我卡在了如何堆叠通知上,就像这里描述的那样。

我想要做什么

我的应用中有两种类型的通知,使用来自GCM服务的数据:

类型1(消息):

[data] => Array
(
    [t] => 1
    [other data...]
)

类型2(新闻):

[data] => Array
(
    [t] => 2
    [other data...]
)

这两种类型的通知完全不同,我想把它们分开堆叠,但是我无法实现这个功能。当有多个通知时,我希望将它们堆叠在一起,如下所示:

默认视图
Stacking Notifications


扩展视图
Stacking Notifications 2


我尝试过的方法

使用2个通知ID和原子整数
我尝试使用2个不同的通知ID,以便具有相同类型的通知被覆盖。

if (msg.get("t").toString().equals("1")) {
    notificationNumber = messageCounter.incrementAndGet();
} else {
    notificationNumber = newsCounter.incrementAndGet();
}
[...]
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
    .setNumber(notificationNumber);

如果同时发送2条消息,一切正常,计数器显示2。但是如果两个通知之间有短暂的延迟,计数器会切换到1。
唯一通知ID 我还尝试使用生成的唯一ID。
Date now = new Date();
Notification_id = now.getTime();

确保没有任何堆叠或覆盖。

问题

如何解决我的问题?我能否访问以前发送的通知内容,以便像 Gmail 的展开视图中一样将每条消息显示在一行中?我该如何检查当前显示的通知数量?
问题很长,非常感谢!


2
你混淆了通知编号(作为通知的一部分显示)和通知ID(控制覆盖通知),不清楚你想要实现什么。 - Eran
1个回答

7

我最终找到了解决方案,并使用原子整数,在一个单独的类中实现:

import java.util.concurrent.atomic.AtomicInteger;

public class Global {
    public static AtomicInteger Counter1 = new AtomicInteger();
    public static AtomicInteger Counter2 = new AtomicInteger();
}

为了在应用程序开启后重置计数器,我在我的MainActivity中添加了以下代码(在onCreate()onResume()中调用):
private void clearNotifications(){        
    NotificationManager mNotificationManager;
    mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.cancelAll();

    Global.Counter1.set(0);
    Global.Counter2.set(0);
}

当我创建通知时,我会检查计数器:
Counter1 = Global.Counter1.incrementAndGet();
ContentText = (Counter1 < 2) ? /* Single notification */ : /* Stacking */;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接