How to collapse Android notifications?

2020-02-11 09:45发布

I'm sending a C2DM update to my Android app every 1/2 hour, which creates a Notification. Problem is, when I wake up in the morning I get 15 Notifications queued up in the status bar.

How do I only keep the latest notification, overwriting previous ones?

I tried looking at the C2DM documentation (http://code.google.com/android/c2dm/) which mentions a parameter called collapse_key, but I couldn't find an explanation for how to use it, nor am I sure the solution lies on the C2DM side.

Thanks!

4条回答
Viruses.
2楼-- · 2020-02-11 10:06

Notification has a property called number that shows a little number below the icon (for multiple notification). It lets you use the same Icon for Multiple Notification.

Use the same ID while updating your notification. :) Cheers.

查看更多
相关推荐>>
3楼-- · 2020-02-11 10:06

collapse_id key should do the job. For updating any previous notification, just use the same key. To generate a new notification on device, use a different key.

For example, * for chat notifications use the key "chat" (collapse_id = "chat") * for invitations use the key "invite" (collapse_id = "invite")

So all the unqiue collapse_id notifications will group on device.

For more details visit: https://documentation.onesignal.com/reference#create-notification

查看更多
▲ chillily
4楼-- · 2020-02-11 10:18

If you want to cancel any previous notifications that has been set on the view you can try setting one of these flags.

PendingIntent.FLAG_CANCEL_CURRENT or  PendingIntent.FLAG_UPDATE_CURRENT 

Something like this should replace your old notification i believe

 NotificationManager mManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
 Intent intent = new Intent(this,test.class);
 Notification notification = new Notification(R.drawable.icon, "Notify", System.currentTimeMillis());
 notification.setLatestEventInfo(this,"App Name","Description of the notification",
 PendingIntent.getActivity(this.getBaseContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
 mManager.notify(0, notification);
查看更多
beautiful°
5楼-- · 2020-02-11 10:30

In addition to the other answers, there is a parameter in your C2DM request that is called delay_while_idle. Make sure you are NOT including that or make it false. Your phone is "idle" when the screen is off (ie while you are sleeping). Google queues up all your messages on the server until the phone is not idle (ie when you turn on the screen in the morning). Then, Google sends all 15 messages at once and you display them at that time.

In the chrome to phone source, there is a method called sendNoRetry with this line:

if (delayWhileIdle) {
            postDataBuilder.append("&")
                .append(PARAM_DELAY_WHILE_IDLE).append("=1");
}

Make sure it is not true, then Google servers will send you your C2DM message every 30 minutes as expected.

查看更多
登录 后发表回答