Показать несколько уведомлений при получении уведомления gcm

Я показываю уведомление на панели уведомлений, как это. Я получаю их, но я не могу показывать там несколько уведомлений, только по одному. Когда приходит новый, предыдущий уходит. В чем проблема?

 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);


    }}

person jihbvsdfu    schedule 27.09.2012    source источник


Ответы (4)


В зависимости от того, сколько уведомлений вам нужно, есть несколько решений. Вы можете добавить идентификатор, который увеличивается в вашем уведомлении, чтобы он имел другое имя и поэтому не заменял другой с тем же идентификатором, или если вам нужно только два уведомления максимум, просто создайте второе уведомление с другими именами строк/переменных ты используешь.

Посмотрите здесь приращение идентификатора:

Android: управление несколькими уведомлениями

Если вам просто нужно второе или третье уведомление, измените свои строки на что-то вроде этого, например:

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);


}}

Надеюсь, вы уловили суть и она вам поможет.

person SunnySonic    schedule 27.09.2012

Используйте этот код, чтобы вывести несколько уведомлений в список int NOTIFICATION_ID = 0; notificationManager.notify(NOTIFICATION_ID, notification2); NOTIFICATION_ID++

person Narendra Kumar    schedule 25.09.2014

@SunnySonic, вам нужно использовать последнюю стабильную версию «Библиотеки поддержки Android».

Чтобы загрузить последнюю стабильную версию «Android Support Libraray», перейдите в «Диспетчер SDK» -> «Дополнительно» -> нажмите «Библиотека поддержки 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')

}
person Sohail    schedule 20.05.2015

Вы можете сгенерировать случайное число как NotificationId в методе уведомления.

notifyManager.notify(generateRandom(),notificationBuilder.build());

public int generateRandom()
{
    Random rn = new Random();
    int n = maximum - minimum + 1;
    int i = rn.nextInt() % n;
    return  minimum + i;

}
person Akash Bisariya    schedule 20.10.2016