Firebase onMessageReceived no se llama cuando la aplicación en segundo plano


Estoy trabajando con Firebase y probando el envío de notificaciones a mi aplicación desde mi servidor mientras la aplicación está en segundo plano. La notificación se envía correctamente, incluso aparece en el centro de notificaciones del dispositivo, pero cuando aparece la notificación o incluso si hago clic en ella, el método onMessageReceived dentro de my FCMessagingService nunca se llama.

Cuando probé esto mientras mi aplicación estaba en primer plano, se llamó al método onMessageReceived y todo funcionó bien. El problema ocurre cuando la aplicación se está ejecutando en segundo plano.

¿Es este comportamiento intencionado, o hay alguna manera de arreglarlo?

Aquí está mi FBMessagingService:

import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class FBMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.i("PVL", "MESSAGE RECEIVED!!");
        if (remoteMessage.getNotification().getBody() != null) {
            Log.i("PVL", "RECEIVED MESSAGE: " + remoteMessage.getNotification().getBody());
        } else {
            Log.i("PVL", "RECEIVED MESSAGE: " + remoteMessage.getData().get("message"));
        }
    }
}
Author: Frank van Puffelen, 2016-05-21

23 answers

Esto funciona según lo previsto, los mensajes de notificación se envían a su devolución de llamada onMessageReceived solo cuando su aplicación está en primer plano. Si la aplicación está en segundo plano o cerrada, se muestra un mensaje de notificación en el centro de notificaciones y todos los datos de ese mensaje se pasan a la intent que se inicia como resultado de que el usuario toque la notificación.

Puede especificar un click_action para indicar la intent que se debe iniciar cuando el la notificación es tocada por el usuario. La actividad principal se utiliza si no se especifica click_action.

Cuando se lanza la intent, puede usar el

getIntent().getExtras();

Para recuperar un Conjunto que incluiría cualquier dato enviado junto con el mensaje de notificación.

Para más información sobre el mensaje de notificación, véase docs.

 88
Author: Arthur Thompson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-23 14:24:26

SOLUCIÓN OBSOLETA:

Tengo una solución perfecta para esto:

Necesitas realizar 2 sencillos pasos:

  1. Actualiza tu firebase a la versión compile com.google.firebase:firebase-messaging:10.2.1
  2. Invalida el método handleIntent(Intent intent) en tu clase FirebaseMessagingService.

handleIntent() el método se llama cada vez si la aplicación está en primer plano, en segundo plano o en estado muerto.

 59
Author: manas.abrol,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-03 08:02:15

Elimine notification el campo completamente de su solicitud de servidor. Enviar solo data y manejarlo en onMessageReceived() de lo contrario su onMessageReceived() no se activará cuando la aplicación está en segundo plano o asesinados.

No olvides incluir el campo "priority": "high" en tu solicitud de notificación. Según la documentación: los mensajes de datos se envían con una prioridad normal, por lo que no llegarán instantáneamente; también podría ser el problema.

Esto es lo que estoy enviando desde servidor

{
  "data":{
    "id": 1,
    "missedRequests": 5
    "addAnyDataHere": 123
  },
  "to": "fhiT7evmZk8:APA91bFJq7Tkly4BtLRXdYvqHno2vHCRkzpJT8QZy0TlIGs......",
  "priority": "high"
}

Para que pueda recibir sus datos en onMessageReceived(RemoteMessage message) así....digamos que tengo que conseguir id

Object obj = message.getData().get("id");
        if (obj != null) {
            int id = Integer.valueOf(obj.toString());
        }
 50
Author: Zohab Ali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-28 12:43:21

Yo tenía el mismo problema. Es más fácil utilizar el "mensaje de datos" en lugar de la 'notificación'. El mensaje de datos siempre carga la clase onMessageReceived.

En esa clase puedes hacer tu propia notificación con notificationbuilder.

Ejemplo:

 @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        sendNotification(remoteMessage.getData().get("title"),remoteMessage.getData().get("body"));
    }

    private void sendNotification(String messageTitle,String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0 /* request code */, intent,PendingIntent.FLAG_UPDATE_CURRENT);

        long[] pattern = {500,500,500,500,500};

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_stat_name)
                .setContentTitle(messageTitle)
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setVibrate(pattern)
                .setLights(Color.BLUE,1,1)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
 24
Author: Koot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-26 21:29:20

Aquí hay conceptos más claros sobre el mensaje de firebase. Lo encontré de su equipo de apoyo.

Firebase tiene tres tipos de mensajes:

Mensajes de notificación : El mensaje de notificación funciona en segundo plano o en primer plano. Cuando la aplicación está en segundo plano, los mensajes de notificación se envían a la bandeja del sistema. Si la aplicación está en primer plano, los mensajes son manejados por onMessageReceived() o didReceiveRemoteNotification callbacks. Estos son esencialmente lo que se conoce como Pantalla mensaje.

Data messages: En la plataforma Android, el mensaje de datos puede funcionar en segundo plano y en primer plano. El mensaje de datos será manejado por onMessageReceived (). Una nota específica de la plataforma aquí sería: En Android, la carga útil de datos se puede recuperar en la Intent utilizada para iniciar su actividad. Para elaborar, si tiene "click_action":"launch_Activity_1", puede recuperar esta intent a través de getIntent() desde solo Activity_1.

Mensajes con notificaciones y cargas útiles de datos: Cuando están en segundo plano, las aplicaciones reciben la carga útil de notificación en la bandeja de notificaciones y solo manejan la carga útil de datos cuando el usuario toca la notificación. Cuando está en primer plano, su aplicación recibe un objeto de mensaje con ambas cargas útiles disponibles. En segundo lugar, el parámetro click_action se utiliza a menudo en la carga útil de notificación y no en la carga útil de datos. Si se usa dentro de la carga útil de datos, este parámetro se tratará como un par clave-valor personalizado y, por lo tanto, deberá implementar una lógica personalizada para que funcione como destinado.

También le recomiendo usar el método onMessageReceived (ver Mensaje de datos) para extraer el paquete de datos. Desde tu lógica, he comprobado el objeto bundle y no he encontrado el contenido de datos esperado. He aquí una referencia a un caso similar que podría aportar más claridad.

Para más información visita mi este hilo

 20
Author: Md. Sajedul Karim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:37

Según la documentación de Firebase Cloud Messaging: Si la actividad está en primer plano, se llamará a onMessageReceived. Si la actividad está en segundo plano o cerrada, el mensaje de notificación se muestra en el centro de notificaciones para la actividad del lanzador de aplicaciones. Puede llamar a su actividad personalizada al hacer clic en la notificación si su aplicación está en segundo plano llamando a rest service api para firebase messaging como:

URL - https://fcm.googleapis.com/fcm/send

Tipo de método- POST

Header- Content-Type:application/json
Authorization:key=your api key

Cuerpo / carga útil:

{ "notification": {
    "title": "Your Title",
    "text": "Your Text",
     "click_action": "OPEN_ACTIVITY_1" // should match to your intent filter
  },
    "data": {
    "keyname": "any value " //you can get this data as extras in your activity and this data is optional
    },
  "to" : "to_id(firebase refreshedToken)"
} 

Y con esto en su aplicación puede agregar el siguiente código en su actividad para ser llamado:

<intent-filter>
                <action android:name="OPEN_ACTIVITY_1" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
 17
Author: Ankit Adlakha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-02 18:01:40

Si la aplicación está en el modo de fondo o inactiva(muerta), y haga clic en en Notificación, debe verificar la carga útil en LaunchScreen(en mi caso, la pantalla de inicio es MainActivity.Java).

Así que en MainActivity.java on onCreate check for Extras :

    if (getIntent().getExtras() != null) {
        for (String key : getIntent().getExtras().keySet()) {
            Object value = getIntent().getExtras().get(key);
            Log.d("MainActivity: ", "Key: " + key + " Value: " + value);
        }
    }
 11
Author: Gent Berani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-19 10:03:57

Invalida el método handleIntent de FirebaseMessageService funciona para mí.

Aquí el código en C# (Xamarin)

public override void HandleIntent(Intent intent)
{
    try
    {
        if (intent.Extras != null)
        {
            var builder = new RemoteMessage.Builder("MyFirebaseMessagingService");

            foreach (string key in intent.Extras.KeySet())
            {
                builder.AddData(key, intent.Extras.Get(key).ToString());
            }

            this.OnMessageReceived(builder.Build());
        }
        else
        {
            base.HandleIntent(intent);
        }
    }
    catch (Exception)
    {
        base.HandleIntent(intent);
    }
}

Y ese es el Código en Java

public void handleIntent(Intent intent)
{
    try
    {
        if (intent.getExtras() != null)
        {
            RemoteMessage.Builder builder = new RemoteMessage.Builder("MyFirebaseMessagingService");

            for (String key : intent.getExtras().keySet())
            {
                builder.addData(key, intent.getExtras().get(key).toString());
            }

            onMessageReceived(builder.build());
        }
        else
        {
            super.handleIntent(intent);
        }
    }
    catch (Exception e)
    {
        super.handleIntent(intent);
    }
}
 8
Author: t3h Exi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-29 15:58:01

Tengo el mismo problema. Si la aplicación está en primer plano, activa mi servicio en segundo plano donde puedo actualizar mi base de datos en función del tipo de notificación. Pero, la aplicación pasa a segundo plano - la notificación predeterminada servicio será atendido para mostrar la notificación al usuario.

Aquí está mi solución para identificar la aplicación en segundo plano y activar su servicio en segundo plano,

public class FirebaseBackgroundService extends WakefulBroadcastReceiver {

  private static final String TAG = "FirebaseService";

  @Override
  public void onReceive(Context context, Intent intent) {
    Log.d(TAG, "I'm in!!!");

    if (intent.getExtras() != null) {
      for (String key : intent.getExtras().keySet()) {
        Object value = intent.getExtras().get(key);
        Log.e("FirebaseDataReceiver", "Key: " + key + " Value: " + value);
        if(key.equalsIgnoreCase("gcm.notification.body") && value != null) {
          Bundle bundle = new Bundle();
          Intent backgroundIntent = new Intent(context, BackgroundSyncJobService.class);
          bundle.putString("push_message", value + "");
          backgroundIntent.putExtras(bundle);
          context.startService(backgroundIntent);
        }
      }
    }
  }
}

En el manifiesto.xml

<receiver android:exported="true" android:name=".FirebaseBackgroundService" android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </receiver>

Probó esta solución en la última versión de Android 8.0. Gracias

 6
Author: Nagendra Badiganti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-20 12:35:56

De forma predeterminada, la Actividad Launcher en su aplicación se iniciará cuando su aplicación esté en segundo plano y haga clic en la notificación, si tiene alguna parte de datos con su notificación, puede manejarla en la misma actividad de la siguiente manera,

if(getIntent().getExtras()! = null){
  //do your stuff
}else{
  //do that you normally do
}
 5
Author: Uzair,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-18 05:34:04

He implementado esta forma fácil de enviar mensajes incluso si la aplicación está cerrada, en segundo plano y en primer plano también. Anteriormente estaba usando la consola firebase pero solo obtengo mensajes, no imágenes y datos personalizados.

Para enviar estos datos personalizados con imagen puedes usar una herramienta llamada AdvancedREST Client, es una extensión de Chrome, y enviar un mensaje con los siguientes parámetros:

Rest client tool Link: https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo

Utilice este url:- https://fcm.googleapis.com/fcm/send Content-Type:application/json Authorization:key=Your Server key From or Authorization key (véase más abajo ref)

{ "data": 
  { "image": "https://static.pexels.com/photos/4825/red-love-romantic-flowers.jpg", 
    "message": "Firebase Push Message Using API" 
    "AnotherActivity": "True" 
  }, 
  "to" : "device id Or Device token" 
}

La clave de autorización se puede obtener visitando Google developers consola y haga clic en el botón Credenciales en el menú de la izquierda para su proyecto. Entre las claves API enumeradas, la clave de servidor será su clave de autorización.

Y necesitas poner tokenID del receptor en la sección to de tu solicitud POST enviada usando API.

Y esta pieza de Android code / / mensaje contendrá el Mensaje Push

String message = remoteMessage.getData().get("message1");

//imageUri will contain URL of the image to be displayed with Notification
String imageUri = remoteMessage.getData().get("image");

//If the key AnotherActivity has  value as True then when the user taps on notification, in the app AnotherActivity will be opened.
//If the key AnotherActivity has  value as False then when the user taps on notification, in the app MainActivity2 will be opened.
String TrueOrFlase = remoteMessage.getData().get("AnotherActivity");

//To get a Bitmap image from the URL received
bitmap = getBitmapfromUrl(imageUri);

sendNotification(message, bitmap, TrueOrFlase);
 5
Author: Syed Danish Haider,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-24 14:36:19

Simplemente llame a esto en el método onCreate de su MainActivity:

if (getIntent().getExtras() != null) {
           // Call your NotificationActivity here..
            Intent intent = new Intent(MainActivity.this, NotificationActivity.class);
            startActivity(intent);
        }
 2
Author: Shekhar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-07 06:59:14

De acuerdo con la solución de t3h Exi me gustaría publicar el código limpio aquí. Solo tienes que ponerlo en MyFirebaseMessagingService y todo funciona bien si la aplicación está en modo de fondo. Necesitas al menos compilar com.Google.firebase: firebase-mensajería: 10.2.1

 @Override
public void handleIntent(Intent intent)
{
    try
    {
        if (intent.getExtras() != null)
        {
            RemoteMessage.Builder builder = new RemoteMessage.Builder("MyFirebaseMessagingService");

            for (String key : intent.getExtras().keySet())
            {
                builder.addData(key, intent.getExtras().get(key).toString());
            }



           onMessageReceived(builder.build());
        }
        else
        {
            super.handleIntent(intent);
        }
    }
    catch (Exception e)
    {
        super.handleIntent(intent);
    }
}
 2
Author: Frank,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-26 12:58:50

Si la aplicación está en segundo plano Fire-base por defecto el manejo de la notificación, Pero si queremos que nuestra notificación personalizada que tenemos que cambiar nuestro lado del servidor, que es responsable de enviar nuestros datos personalizados(carga útil de datos)

Elimine la carga útil de notificación completamente de su solicitud de servidor. Envía solo Datos y manéjalos en onMessageReceived () de lo contrario, tu onMessageReceived no se activará cuando la aplicación esté en segundo plano o muerta.

Ahora, su aspecto de formato de código del lado del servidor como,

{
  "collapse_key": "CHAT_MESSAGE_CONTACT",
  "data": {
    "loc_key": "CHAT_MESSAGE_CONTACT",
    "loc_args": ["John Doe", "Contact Exchange"],
    "text": "John Doe shared a contact in the group Contact Exchange",
    "custom": {
      "chat_id": 241233,
      "msg_id": 123
    },
    "badge": 1,
    "sound": "sound1.mp3",
    "mute": true
  }
}

NOTA : ver esta línea en el código anterior
"texto": "John Doe compartió un contacto en el Intercambio de contactos del grupo" en la carga útil de datos debe usar el parámetro " texto "en lugar de los parámetros" cuerpo "o" mensaje " para la descripción del mensaje o lo que quiera usar texto.

Un mensaje recibido()

@Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e(TAG, "From: " + remoteMessage.getData().toString());

        if (remoteMessage == null)
            return;

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
           /* Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());*/
            Log.e(TAG, "Data Payload: " + remoteMessage);

            try {

                Map<String, String> params = remoteMessage.getData();
                JSONObject json = new JSONObject(params);
                Log.e("JSON_OBJECT", json.toString());


                Log.e(TAG, "onMessageReceived: " + json.toString());

                handleDataMessage(json);
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }
    }
 2
Author: Hiren,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-07 09:51:45

Prueba esto:

public void handleIntent(Intent intent) {
    try {
        if (intent.getExtras() != null) {
            RemoteMessage.Builder builder = new RemoteMessage.Builder("MyFirebaseMessagingService");
            for (String key : intent.getExtras().keySet()) {
            builder.addData(key, intent.getExtras().get(key).toString());
        }
            onMessageReceived(builder.build());
        } else {
            super.handleIntent(intent);
        }
    } catch (Exception e) {
        super.handleIntent(intent);
    }
}
 2
Author: user3587828,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-21 05:46:37

Tuve este problema(la aplicación no quiere abrirse en la notificación, haga clic en si la aplicación está en segundo plano o cerrada), y el problema era un click_action no válido en el cuerpo de la notificación, intente eliminarlo o cambiarlo a algo válido.

 1
Author: Octavian Lari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-23 14:11:18

Estaba teniendo el mismo problema e investigué un poco más sobre esto. Cuando la aplicación está en segundo plano, se envía un mensaje de notificación a la bandeja del sistema, PERO se envía un mensaje de datos a onMessageReceived()
Véase https://firebase.google.com/docs/cloud-messaging/downstream#monitor-token-generation_3
y https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/MyFirebaseMessagingService.java

Para asegurarse de que el mensaje que está enviando, los documentos dicen: "Use su servidor de aplicaciones y FCM server API: Establezca solo la clave de datos. Puede ser plegable o no plegable."
Véase https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages

 1
Author: Eric B.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-19 19:47:21

El punto que merece destacarse es que debe usar data message - data key only - para que se llame al controlador onMessageReceived incluso cuando la aplicación está en segundo plano. No debe tener ninguna otra clave de mensaje de notificación en su carga útil, de lo contrario, el controlador no se activará si la aplicación está en segundo plano.

Se menciona (pero no se enfatiza así en la documentación de FCM) aquí:

Https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages

Utilice el servidor de aplicaciones y la API del servidor FCM: Establezca la clave de datos solo. Puede ser plegable o no plegable.

 1
Author: n_y,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-18 11:24:25

El backend con el que estoy trabajando está usando Mensajes de notificación y no mensajes de datos. Así que después de leer todas las respuestas traté de recuperar los extras del paquete de la intención que viene a la actividad lanzada. Pero no importa qué claves traté de recuperar de getIntent().getExtras();, el valor siempre era null.

Sin embargo, finalmente encontré una manera de enviar datos usando Mensajes de notificación y recuperarlos de la intent.

La clave aquí es agregar los datos payload al mensaje de notificación.

Ejemplo:

{
    "data": {
        "message": "message_body",
        "title": "message_title"
    },
    "notification": {
        "body": "test body",
        "title": "test title"
    },
    "to": "E4An.."
}

Después de hacer esto, usted será capaz de obtener su información de esta manera:

intent.getExtras().getString("title") será message_title

Y intent.getExtras().getString("message") será message_body

Referencia

 1
Author: Vito Valov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-24 22:27:04

Si su problema está relacionado con mostrar una imagen grande, es decir, si está enviando una notificación push con una imagen desde firebase console y muestra la imagen solo si la aplicación está en primer plano. La solución para este problema es enviar un mensaje push con solo el campo de datos. Algo como esto:

{ "data": { "image": "https://static.pexels.com/photos/4825/red-love-romantic-flowers.jpg", "message": "Firebase Push Message Using API" "AnotherActivity": "True" }, "to" : "device id Or Device token" }
 1
Author: Arun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-28 16:38:07

Hay dos tipos de mensajes: mensajes de notificación y mensajes de datos. Si solo envía un mensaje de datos, es decir, sin objeto de notificación en su cadena de mensaje. Se invocaría cuando su aplicación en segundo plano.

 0
Author: Shongsu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-17 15:18:27

Cuando se recibe un mensaje y tu app está en segundo plano, la notificación se envía a la intent extras de la actividad principal.

Puede comprobar el valor extra en la función oncreate() o onresume() de la actividad principal.

Puede verificar los campos como datos, tabla, etc. (el especificado en la notificación)

Por ejemplo, envié usando datos como clave

public void onResume(){
    super.onResume();
    if (getIntent().getStringExtra("data")!=null){
            fromnotification=true;
            Intent i = new Intent(MainActivity.this, Activity2.class);
            i.putExtra("notification","notification");
            startActivity(i);
        }

}
 0
Author: Sanjeev S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-28 09:23:39

Simplemente anule el método onCreate de FirebaseMessagingService. Se llama cuando su aplicación está en segundo plano:

public override void OnCreate()
{
    // your code
    base.OnCreate();
}
 -2
Author: Renzo Ciot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-01 14:55:29