Handle multiple Notifications / Stacking Notificat

2020-05-27 05:01发布

问题:

I just implemented GCM and notifications in my Android app, coming from an Apache/PHP-based webserver.
The notifications are already working, but I'm stuck at stacking the notifications, as described here.

What I'm trying to do

I have two types of notifications in my app, using data coming from the GCM Service:

Type 1 (Messages):

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

Type 2 (News):

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

These 2 types are completely different notifications, and I would like to stack both of them separate from each other, but I can't get this to work. I would like to stack them like this, as soon as there are multiple notifications:

Default View


Expanded View


What I tried

2 Notification IDs and Atomic Integer
I tried to use 2 different notification IDs, so that notifications with the same type get overidden.

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

If 2 messages are sent at the same time, everything works fine and the counter shows 2. But if there is a short delay between two notifications, the counter switches to 1.

Unique Notification IDs
I also tried to use unique IDs generated with

Date now = new Date();
Notification_id = now.getTime();

so that there isn't no stacking or overriding at all.

Question

How can I solve my problem? Can I access the content of the previously sent notifications, so that I can show every message in one line, like in the expanded view of Gmail? How can I check which / how many notifications are currently displayed?
Long question, thank you very much!

回答1:

I finally found the solution and ended up using atomic integers, but in a seperated class:

import java.util.concurrent.atomic.AtomicInteger;

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

To reset the counter after the application opening, i put this in my MainActivity (called in onCreate() and onResume():

private void clearNotifications(){        
    NotificationManager mNotificationManager;
    mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.cancelAll();

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

When I create the notification, I check the counter:

Counter1 = Global.Counter1.incrementAndGet();
ContentText = (Counter1 < 2) ? /* Single notification */ : /* Stacking */;