Android 收到推送通知时添加新通知(不替换以前的通知)
我正在应用程序中使用推送通知。我需要在发送推送通知时显示通知。如果我发送另一个通知(不清除以前的通知),它将替换旧通知Android 收到推送通知时添加新通知(不替换以前的通知),android,notifications,notificationmanager,Android,Notifications,Notificationmanager,我正在应用程序中使用推送通知。我需要在发送推送通知时显示通知。如果我发送另一个通知(不清除以前的通知),它将替换旧通知 int id = (int) System.currentTimeMillis(); mNotificationManager.notify(id, notification); 这是我使用的代码: NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context
int id = (int) System.currentTimeMillis();
mNotificationManager.notify(id, notification);
这是我使用的代码:
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.ic_launcher;
CharSequence tickerText = "New notification Pending";
long time = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, time);
notification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL;
// Context context = getApplicationContext();
CharSequence contentTitle = "Notifications";
CharSequence contentText = newMessage;
Intent notificationIntent = new Intent(this, LoginActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);
mNotificationManager.notify(1, notification);
但我不想替换通知,我想将其添加为新通知。简单,您必须
int id = (int) System.currentTimeMillis();
mNotificationManager.notify(id, notification);
更改通知id
mNotificationManager.notify(1, notification);
而不是1
有关更多信息,请参阅每次使用新的通知ID,而不是硬编码为1:
int i = x; //Generate a new integer everytime
mNotificationManager.notify(i, notification);
每次都需要提供不同的ID作为通知ID。最好的方法是向GCM发送一个ID字段,然后可以通过GCMinentService的onMessage()方法中的
Intent.getExtras().getInt()
访问该字段
如果这不可能,我建议使用类似于
(int)Math.random()*10
的方法生成一个随机整数作为通知ID。这将(部分)确保您的通知不会相互替换。您还可以使用System.currentTimeMillis()为通知分配唯一的ID
int id = (int) System.currentTimeMillis();
mNotificationManager.notify(id, notification);
我不确定您的用例是什么,但是 不要: 做:
我们需要唯一的通知id,它将生成新的通知 发布要在状态栏中显示的通知。如果通知 您的应用程序已经发布了相同的id,但尚未取消,它将被更新的信息替换
@param id An identifier for this notification unique within your application.
@param notification A {@link Notification} object describing what to show the user.
Must not be null.
public void notify(int id, Notification notification)
{
notify(null, id, notification);
}
例如:
int id =(int) System.currentTimeMillis();
mNotificationManager.notify(id, notify);
这是个好主意。因为时间id永远不会重复。我在php中也使用同样的方法。谢谢但将代码更改为notify(id,notification);这对于其他Hanks Indra来说可能很有用,现在我用id.thanqu代替了1,先生..因为我认为这完全取决于用例,现在多亏了通知渠道,人们可以更清楚地了解这一点,这很奇怪。如果您在一个应用程序中有几个不同的事件,比如聊天、订单确认、付款状态,该怎么办?