I am using FCM since version 8.0, As per documentation, data in the notification
will be received only when the app is in the foreground in the FCMMessagingService
, but data in the data
key will be received in both situations, doesn't matter if the app is in foreground or background.
Below is the PHP snippet by which server sends a notification
$path_to_firebase_cm = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'to' => $token,
'notification' => array('title' => 'Title', 'body' => $message,'vibrate'=>"1",'sound'=>"mySound"),
'data' => array('message' => $message)
);
Android code/class that should receive notification.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData().get("message"));
sendNotification(remoteMessage.getData().get("message"));
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
}
}
}
compile 'com.google.firebase:firebase-messaging:10.0.1'
Plugin, classpath, and service in manifiest are already added as per requirement
apply plugin: 'com.google.gms.google-services'
classpath 'com.google.gms:google-services:3.0.0'
<service android:name=".fcm.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".fcm.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
ISSUE
When the app is in foreground, data payload and notification payload both log are displaying and when the app is in background none of the log is getting displayed.
It is working fine with the old projects, an issue is with when we create new Firebase app, that is giving new LEGACY SERVER KEY for sending the notification.
You must use only
data
object on your json. See this. So your json must be like this