我正在通知栏上显示通知。我收到了这些,但我不能在那里显示多个通知,一次只能显示一个。当一个新的到来时,前一个去。问题是什么?
public void createNotificationRecever(Context context, String payload) {
Toast.makeText(context, commentor + "commented on your post " ,Toast.LENGTH_LONG).show();
//New message received
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.flag,
payload, System.currentTimeMillis());
// Hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(context, MessageReceivedActivity.class);
intent.putExtra("id", groupid);
intent.putExtra("userid", text);
intent.putExtra("cname", groupname);
intent.putExtra("image", "");
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
intent, 0);
notification.setLatestEventInfo(context, "Message",
payload, pendingIntent);
notificationManager.notify(0, notification);
}}
答案 0 :(得分:5)
根据您需要的通知数量,有几种解决方案。您可以添加一个增加到您的通知的ID,因此它将具有不同的名称,因此不会使用相同的ID替换另一个,或者如果您只需要两个通知max,则只需创建具有不同名称的字符串/变量的第二个通知你正在使用。
在这里查看ID增量:
Android: Managing Multiple Notifications
如果您只需要第二次或第三次通知,请将字符串更改为类似的内容,例如:
public void createNotificationRecever(Context context2, String payload2) {
Toast.makeText(context2, commentor + "commented on your post " ,Toast.LENGTH_LONG).show();
//New message received
NotificationManager notificationManager = (NotificationManager) context2
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification2 = new Notification(R.drawable.flag,
payload2, System.currentTimeMillis());
// Hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(context2, MessageReceivedActivity.class);
intent.putExtra("id", groupid2);
intent.putExtra("userid", text2);
intent.putExtra("cname", groupname2);
intent.putExtra("image", "");
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
intent, 0);
notification.setLatestEventInfo(context, "Message",
payload, pendingIntent);
notificationManager.notify(0, notification2);
}}
我希望你能得到主旨,这对你有帮助。
答案 1 :(得分:5)
使用此代码,它会在列表中显示多个通知
int NOTIFICATION_ID = 0;
notificationManager.notify(NOTIFICATION_ID, notification2);
NOTIFICATION_ID++
答案 2 :(得分:0)
@SunnySonic,您需要使用最新的稳定版本" Android支持库"。
要下载最新稳定版的" Android支持Libraray", 转到SDK Manager - >额外 - >点击Android支持库并进行更新。
并转到build.gradle和"依赖关系",更改版本。
dependencies {
compile 'com.android.support:support-v4:22.1.1' //<-change this
compile files('libs/bolts-android-1.1.4.jar')
compile files('libs/gcm.jar')
}
答案 3 :(得分:0)
您可以在notify方法中生成NotificationId的随机数。
notificationManager.notify(generateRandom(),notificationBuilder.build());
public int generateRandom()
{
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
return minimum + i;
}