La notificación push funciona incorrectamente cuando la aplicación está en segundo plano o no se está ejecutando


Estoy usando Firebase Cloud Messaging para enviar notificaciones push.

Aquí está mi FirebaseMessageService:

public class FireBaseMessageService extends FirebaseMessagingService {


@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.e("TAG", "From: " + remoteMessage.getFrom());
    Log.e("TAG", "Notification Message Body: " + remoteMessage.getData().get("CardName")+"  :  "+remoteMessage.getData().get("CardCode"));
    sendNotification(remoteMessage.getNotification().getBody());
}


private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, StartActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher_final)
            .setContentTitle("Notification")
            .setContentText(messageBody)
            .setTicker("Test")
            .setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_SOUND)
            .setContentIntent(pendingIntent);

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

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

Y FirebaseInstanceServer:

public class FirebaseInstanceService extends FirebaseInstanceIdService {


@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.e("TAG", "Refreshed token: " + refreshedToken);

    // TODO: Implement this method to send any registration to your app's servers.
    sendRegistrationToServer(refreshedToken);

}

private void sendRegistrationToServer(String token) {


      // Add custom implementation, as needed.
        Log.e("TAG", "Refreshed token2: " + token);
    }
}

Que se declara en el AndroidManifest:

<service
    android:name=".util.notifications.FireBaseMessageService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

<service
    android:name=".util.notifications.FirebaseInstanceService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
</service>

Así que el problema es que cuando la aplicación se está ejecutando ticker se muestra bien y la notificación viene con sonido predeterminado, pero cuando la aplicación está en primer plano o no se está ejecutando la notificación viene sin ningún sonido y ticker no se muestra en la barra de estado.
¿Por qué sucede esto y cómo puedo arreglarlo?

Author: Paul Stenne, 2016-06-17

2 answers

Con FCM se especifica una carga POST para enviar a https://fcm.googleapis.com/fcm/send. En ese payload puede especificar una clave data o notification, o ambas.

Si su carga útil contiene solo una clave data, su aplicación manejará todos los mensajes push por sí misma. Por ejemplo, todos se entregan a su controlador onMessageReceived.

Si tu carga contiene una clave notification, tu app manejará los mensajes push por sí misma solo si tu app está activa/en primer plano. Si no lo es (por lo que está en segundo plano, o cerrado por completo), FCM maneja mostrando la notificación por usted usando los valores que puso en la carga útil de la clave notification.

Tenga en cuenta que las notificaciones enviadas desde una consola (como Firebase console), siempre incluyen una tecla notification.

Parece que quieres manejar los mensajes de FCM tú mismo para que puedas personalizar la notificación un poco más, etc., por lo que sería mejor no incluir la clave notification en la carga POST, para que todos los mensajes push se entreguen a tu onMessageReceived.

Puedes leer más sobre está aquí.:
Opciones avanzadas de mensajería
Sintaxis del mensaje descendente

 55
Author: Tim Castelijns,
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-18 11:24:23

Pasé 2 semanas para entender por qué mi aplicación ya no puede recibir mensajes de datos cuando está en segundo plano y tan extraño como podría ser, llegué a la conclusión de que Android-Studio 2.1.2 es el problema!

Ya no puedo recibir ningún mensaje de FCM en la aplicación en segundo plano

Https://github.com/firebase/quickstart-android/issues/89

 2
Author: fralbo,
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 11:54:58