处理来自GCM的多个通知/堆叠通知

时间:2014-02-28 17:30:59

标签: android notifications push-notification google-cloud-messaging

我刚在Android应用中实现了GCM和通知,来自基于Apache / PHP的网络服务器 通知已经有效,但我仍然坚持堆叠通知,如here所述。

我正在尝试做什么

我的应用中有两种类型的通知,使用来自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的展开式视图中?如何查看当前显示的通知数量/数量? 很长的问题,非常感谢你!

1 个答案:

答案 0 :(得分: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 */;
相关问题