Android 如何使用FirebaseMessagingService计算通知数?
我正在开发一个使用Firebase的通知推送的系统。我的问题是,当用户单击通知时,我需要计算通知的数量并重置计数器(“contador”变量) 计数器的功能是显示下一条消息:“有X个新警报” 在用户第一次收到通知后,此计数器不会递增,并且始终仅显示1个通知,但可能会有更多通知 代码如下:Android 如何使用FirebaseMessagingService计算通知数?,android,notifications,Android,Notifications,我正在开发一个使用Firebase的通知推送的系统。我的问题是,当用户单击通知时,我需要计算通知的数量并重置计数器(“contador”变量) 计数器的功能是显示下一条消息:“有X个新警报” 在用户第一次收到通知后,此计数器不会递增,并且始终仅显示1个通知,但可能会有更多通知 代码如下: public class MiFirebaseMessagingService extends FirebaseMessagingService { NotificationCompat.Builder
public class MiFirebaseMessagingService extends FirebaseMessagingService {
NotificationCompat.Builder mBuilder;
int mNotificationId = 1234567;
String titulo = "";
int contador = 0;
JSONArray alertas = new JSONArray();
public static final String TAG = "NOTICIAS";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String from = remoteMessage.getFrom();
Log.d(TAG, "Mensaje recibido de: "+from);
if(remoteMessage.getNotification() != null) {
Log.d(TAG, "Notificacion: " + remoteMessage.getNotification().getBody());
Log.d(TAG, "Zona:" + remoteMessage.getData().get("Zona").toString());
contador++;
Log.d(TAG, "Contador:" + contador);
String cuerpo = "Se han detectado ".concat(String.valueOf(contador)).concat(" nuevas alarmas");
titulo = titulo.concat(remoteMessage.getNotification().getTitle()).concat(",");
JSONObject alerta_actual = new JSONObject();
try {
alerta_actual.put("Variable", remoteMessage.getNotification().getTitle().toString());
alerta_actual.put("Descripcion", remoteMessage.getNotification().getBody().toString());
alerta_actual.put("Zona", remoteMessage.getData().get("Zona").toString());
Log.d(TAG, "Alerta:" + alerta_actual.toString());
alertas.put(alerta_actual);
if(remoteMessage.getData().size() > 0)
{
Log.d(TAG, "Data:"+remoteMessage.getData());
}
mostrarNotificacion(cuerpo);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
另一方面,向用户显示带有计数器的消息的代码如下:
private void mostrarNotificacion(String body) {
Log.d(TAG, alertas.toString());
Log.d(TAG, "Contador:"+String.valueOf(contador));
NotificationManager mNotifyMgr = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
int icono = R.mipmap.ic_launcher;
Intent i = new Intent(this, Notificaciones.class);
i.putExtra("Alertas", alertas.toString());
int uniqueInt = (int) (System.currentTimeMillis() & 0xfffffff);
PendingIntent pendingIntent = PendingIntent.getActivity(this, uniqueInt, i, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setContentIntent(pendingIntent)
.setSmallIcon(icono)
.setContentTitle(titulo)
.setContentText(body)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
mNotifyMgr.notify(1, mBuilder.build());
}
为什么计数器“contador”在第一次之后没有增加?它每次在类的新实例上初始化,您应该将其存储在shaedPreferences中。如果每次在类的新实例上初始化,您应该将其存储在shaedPreferences中