база уведомлений Android

Я отправляю уведомление на Android через PHP, и оно становится нормальным на Android.

Но когда я отправляю больше одного, он показывает только последний, и я хотел, чтобы он показывал все из них.

Является ли это возможным?

Как я могу это сделать?

PHP

$msg = array
(
'nome'  => $comando,
);
$fields = array
(
'to'    => $token,
'data'  => $msg
);$headers = array
(
'Content-Type: application/json',
'Authorization: key= KEY'
);

#Send Reponse To FireBase Server
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );

#Echo Result Of FireBase Server
echo $result;

андроид

Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1410,
intent, PendingIntent.FLAG_UPDATE_CURRENT);

Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setSound(alert)
.setContentTitle("teste")
.setContentText("teste "+msg+"!")
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.setPriority(2)
.setContentIntent(pendingIntent);

NotificationManager notificationManager =
(NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);

notificationManager.notify(1410, notificationBuilder.build());

1

Решение

Это просто:

notificationManager.notify(1410, notificationBuilder.build());

ты написал ‘1410’, Вместо того, чтобы назначить Unique_Integer_number каждый раз.

Чтобы стать уникальным не каждый раз:

Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
2

Другие решения

Удалить 1410 из этой строки и также измените строку PendingIntent.

PendingIntent pendingIntent = PendingIntent.getActivity(this, 1410,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationManager.notify(1410, notificationBuilder.build());

Добавьте эту строку для генерации уникального идентификатора и используйте ее для уведомления.

int id = (int) System.currentTimeMillis();
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notificationManager.notify(id, notificationBuilder.build());
2

Отмените все уведомления перед уведомлением о новом.

NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();

notificationManager.notify(1410, notificationBuilder.build());
1

Проблема в этой линии

 notificationManager.notify(1410, notificationBuilder.build());

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

Простой способ — использовать SharedPreference для получения и сохранения идентификатора. И каждый раз используйте увеличенный. Смотрите пример ниже.

 private int getNotificationId(){
SharedPreferences  sp = PreferenceManager.getDefaultSharedPreferences(this);
int lastId=sp.getInt("notify_id",0);
sp.edit().putInt("notify_id",lastId+1).commit();
return lastId;
}

notificationManager.notify(getNotificationId(), notificationBuilder.build());
1

В коде Android вы используете только один идентификатор уведомления, измените его на динамический, и вы увидите все уведомления.

изменить следующую строку:

notificationManager.notify(getUniqueId(), notificationBuilder.build());

...
private int getUniqueId() {
return (int) (System.currentTimeMillis() / 1000);
}
1

Ты использовал PendingIntent.FLAG_UPDATE_CURRENT и нет уникального идентификатора для каждого Notification, Используйте это для показа Notification

private void sendNotification(String messageBody) {
int uniqueNotificationId = (int) (System.currentTimeMillis() & 0xfffffff);
Intent intent = new Intent(this, LoginActivity.class); // Where you will go after clicking on notification
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, uniqueNotificationId /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);

//PendingIntent pendingIntent= PendingIntent.getActivity(this, uniqueNotificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
android.support.v4.app.NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);

NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

notificationManager.notify(uniqueNotificationId  /* ID of notification */, notificationBuilder.build());
}
1