No puedo conseguir extras de la intención cuando la aplicación está en segundo plano

Rifki Maulana:

Trato de ejecutar una función en mi MainActivity cuando se hace clic en una notificación. La función necesita un dato que puse en extras intención.

El problema es cuando hago clic en la notificación cuando se ejecuta la aplicación se ejecuta la función, pero cuando hago clic en la notificación cuando la aplicación está en el fondo, la función no se ejecuta. Lo he comprobado y es porque los datos que puse en extras intención está vacía cuando la aplicación está en el fondo.

¿Como puedó resolver esté problema? ¡Gracias!

Esta es la respuesta que recibo:

{
    "to":"blablabla",
    "notification": {
        "body":"Sentiment Negative from customer",
        "title":"Mokita"
    },
    "data" : {
        "room_id":1516333
    }
}

Este es mi notificación código:

public void onMessageReceived(RemoteMessage message) {
    super.onMessageReceived(message);
    Log.d("msg", "onMessageReceived: " + message.getData().get("room_id"));
    String roomId = message.getData().get("room_id");

    Intent intent = new Intent(this, HomePageTabActivity.class);
    intent.putExtra("fromNotification", true);
    intent.putExtra("roomId", roomId);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    String channelId = "Default";
    NotificationCompat.Builder builder = new  NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(message.getNotification().getTitle())
            .setContentText(message.getNotification().getBody())
            .setAutoCancel(true)
            .setContentIntent(pendingIntent);
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
        manager.createNotificationChannel(channel);
    }

    manager.notify(0, builder.build());
}

}

Y esta es la función y la forma en que ejecuté en MainActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_drawer);
    onNewIntent(getIntent());
}

@Override
    public void onNewIntent(Intent intent){
        Bundle extras = intent.getExtras();
        if(extras != null){
            if(extras.containsKey("fromNotification") || extras.containsKey("roomId")) {
                openChatRoom(Long.valueOf(extras.getString("roomId")));
            }else if(extras.containsKey("fromNotification") && extras.containsKey("roomId")){
                openChatRoom(Long.valueOf(extras.getString("roomId")));
            }else{
                Log.e("EXTRAS room",""+extras.getString("roomId"));
                Log.e("EXTRAS STATUS",""+extras.getBoolean("fromNotification"));
            }
        }else{
            Toast.makeText(HomePageTabActivity.this,"Empty",Toast.LENGTH_SHORT).show();
        }
    }


public void openChatRoom(long roomId){
        Log.d("LONG ROOM",""+roomId);
        QiscusRxExecutor.execute(QiscusApi.getInstance().getChatRoom(roomId),
        new QiscusRxExecutor.Listener<QiscusChatRoom>() {
            @Override
            public void onSuccess(QiscusChatRoom qiscusChatRoom) {
                startActivity(GroupRoomActivity.
                        generateIntent(HomePageTabActivity.this, qiscusChatRoom));
            }
            @Override
            public void onError(Throwable throwable) {
                throwable.printStackTrace();
            }
        });
    }
Amad Yus:

Firebase tiene dos tipos de mensajes: mensajes de notificación y los mensajes de datos. Si quieres FCM SDK para manejar los mensajes por su cuenta, usted necesita para su uso notification. Cuando la aplicación está inactiva, FCM utilizar notificationel cuerpo para mostrar los mensajes. En este estado, onMessageReceivedtambién no se activará. Si quieres aplicación para procesar los mensajes, es necesario el uso data. Es posible que tenga que cambiar la carga útil de notificación de inserción

{
   "message":{
   "token":"xxxxx:...",
   "notification":{
          "title":"Your title",
          "body":"Your message"
      }
   }
}

a

{
   "message":{
   "token":"xxxxx:...",
   "data":{
          "title":"Your title",
          "body":"Your message",
          "fromNotification":"true",
          "roomId":"123"
      }
   }
}

También es necesario para procesar los mensajes en onMessageReceived(RemoteMessage remoteMessage)consecuencia. Usted puede leer sobre el comportamiento de notificación de notificaciones y mensajes de datos .

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=185306&siteId=1
Recomendado
Clasificación