Tashen Jazbi Tashen Jazbi - 1 year ago 142
PHP Question

onMessageReceived never called in notification from server using Firebase in Android

I'm sending notification from server using Firebase in Android. My code works when I send a notification from Firebase Console, but it doesn't work when I send a message from my server. I turned on debugging and I analyzed that

method of FirebaseMessagingService is never called.

Here is my FirebaseMessagingService code:

public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
private static final String TAG = FirebaseMessagingService.class.getSimpleName();

public void onMessageReceived(RemoteMessage remoteMessage) {


private void showNotification(String message){

Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Firebase Push Notification")
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());

Here is my PHP code of server side"

public function sendPushNotificationToGCMSever($token, $message){

//include_once 'config.php';

$url = 'https://fcm.googleapis.com/fcm/send';

$fields = array(
'registration_ids' => $token,
'notification' => $message

$headers = array(
'Authorization:key=' . SERVER_KEY,
$ch = curl_init();

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

$result = curl_exec($ch);


return $result;

Can anyone tell me what I'm doing wrong? Any help would be much appreciated. Thank you :)

Answer Source

The guide says that (to send a notification like the console does) your $fields should be (if $message is a string)

$fields = array(
                'to' => $token,
                'notification' =>  array(
                       'body' => $message

You can also choose the icon for the notification by setting 'icon' => 'the name of some file in res/drawables' as described in this blog post

Also see the difference between data only messages and notifications in the guide.

If you try data only messages and onMessageReceived, then you possibly forgot to add (as mentioned in the guide)

        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download