Send FCM messages from server side to android device
When transitioning from GCM to Firebase Cloud Messaging (FCM), the architecture for delivering push notifications shifts significantly, particularly when moving from manual testing in a console to asynchronous triggers from your own backend. The core issue often lies not in the message payload or the PHP script used to transmit the data, but in how the Android device handles the incoming RemoteMessage.
Consider a scenario where you have successfully verified connectivity by sending notifications directly from the Firebase Console. This confirms that your server credentials and the target device token are valid. However, when you attempt to replicate this logic using a backend script triggered by an eventâsuch as a user action or cron jobâthe app crashes immediately upon receipt. The logcat output reveals a NullPointerException within MyFirebaseMessagingService.onMessageReceived.
at com.google.firebase.messaging.RemoteMessage$Notification.getBody() on a null object reference
at com.google.firebase.quickstart.fcm.MyFirebaseMessagingService.onMessageReceived(MyFirebaseMessagingService.java:53)
This specific error indicates that the app tried to access the notification body, but the data arrived in a format the receiver didn't expect. This is a classic mismatch between the sender's configuration and the receiver's implementation.
Handling Data vs. Display Notifications
The root cause of the crash described in the logs is likely an attempt to treat a Data Message as a Display Notification. When sending messages via the server-side PHP script you are referencing, Firebase expects specific payloads depending on your intent. If your backend sends a message containing only data fields (like key: value pairs) without wrapping them in a notification object, FCM treats it as a silent data push.
If your Android service implementation assumes every incoming message contains a .getNotification().getBody(), you will encounter the exact NullPointerException observed. The RemoteMessage$Notification object is null because no notification was defined in the request payload.
To resolve this, you must modify your MyFirebaseMessagingService to check if a notification exists before accessing it:
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Check if message contains a data payload or notification object
if (!remoteMessage.getData().isEmpty() && remoteMessage.getNotification() == null) {
// Handle Data Message silently or via your own logic
Log.d("FCM", "Data message received: " + remoteMessage.getData());
// Extract and process data here
String customKey = remoteMessage.getData().get("custom_key");
} else if (remoteMessage.getNotification() != null) {
// Handle Display Notification
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
Log.d("FCM", "Notification received: " + body);
}
}
Server-Side Payload Construction
On the server side, using a standard PHP script to send notifications requires ensuring the payload matches what the Android app expects if you intend for it to show an alert. If you want the message to appear in the notification shade immediately upon receipt, the send API call must include a notification object containing title and body.
However, if your event trigger requires silent data processing (e.g., updating local state or syncing offline queues), sending a notification object is unnecessary and might clutter your logs. The trade-off here is visibility versus efficiency. Display notifications consume battery and screen real estate; data messages are efficient but require explicit handling in the client to be useful.
Conclusion
The transition from GCM to FCM often confuses developers because the payload structure becomes more flexible yet stricter about type checking. By ensuring your onMessageReceived method guards against null notification objects and structuring your backend requests to match the intended delivery mode (display vs. data), you eliminate runtime crashes like the one in the logs. For robust implementation, consider integrating a service dedicated to managing these lifecycle events, which can streamline the handling of both data and display messages without requiring manual payload adjustments for every event type.