Android: Управление несколькими push-уведомлениями в устройстве приложения
Я разрабатываю приложение, в котором я реализовал функциональные возможности Push уведомления.
Мой код onMessage - GCMIntentService.java:
@Override
protected void onMessage(Context context, Intent data) {
String message = data.getExtras().getString("message");
displayMessage(context, message);
generateNotification(context, message);
}
И код generateNotification -
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, GCMMessageView.class);
notificationIntent.putExtra("message", message);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
Этот код работает нормально. Я получаю push-сообщение и уведомление.
= > Но когда я отправляю больше одного сообщения, уведомление начинает писать. И я могу видеть только последнее уведомление в строке состояния.
требуется приложения: если я отправил больше одного уведомления, тогда все должно быть отображено в строке состояния.
Итак, пожалуйста, расскажите мне, что я должен сделать для этого в своем коде.
Ответы
Ответ 1
Попробуйте поместить другой идентификатор уведомления (т.е. nid) в намерение и уведомить вместо 0 для каждого нового уведомления, это будет препятствовать написанию вашего уведомления
PendingIntent intent = PendingIntent.getActivity(context, nid,notificationIntent, 0);
и
notificationManager.notify(nid, notification);
Надеюсь, это поможет вам
Ответ 2
привет, вам нужно передать уникальный идентификатор уведомления в методе уведомления.
Ниже приведен код для уникального идентификатора уведомления:
//"CommonUtilities.getValudeFromOreference" is the method created by me to get value from savedPreferences.
String notificationId = CommonUtilities.getValueFromPreference(context, Global.NOTIFICATION_ID, "0");
int notificationIdinInt = Integer.parseInt(notificationId);
notificationManager.notify(notificationIdinInt, notification);
// will increment notification id for uniqueness
notificationIdinInt = notificationIdinInt + 1;
CommonUtilities.saveValueToPreference(context, Global.NOTIFICATION_ID, notificationIdinInt + "");
//Above "CommonUtilities.saveValueToPreference" is the method created by me to save new value in savePreferences.
Сообщите мне, нужна ли вам дополнительная информация или какой-либо запрос.:)
Ответ 3
Вам нужно обновить Notification ID
при запуске Notification.
в
notificationManager.notify(ID, notification);
Как?
Чтобы настроить уведомление, чтобы оно могло быть другим, введите его с идентификатором уведомления, вызвав NotificationManager.notify(ID, notification).
Чтобы изменить это уведомление после его создания, создайте объект NotificationCompat.Builder
, создайте объект Notification
из его и выдать Notification
с помощью Different ID
, который вы ранее не использовали.
Если предыдущее уведомление все еще отображается, система обновляет его из содержимого Notification object
. Если предыдущее уведомление было отклонено, вместо него создается новое уведомление.
Для получения дополнительной информации перейдите в официальный docs
Ответ 4
Получить случайные числа:
Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
Вместо:
notificationManager.notify(0, notification);
использование:
notificationManager.notify(m, notification);
Ответ 5
notificationManager.notify(Different_id_everytime, notification);