Send FCM messages from the server to an Android device

With the new update, FCM will now be used.

I tried the sample application from git and it worked perfectly. I can send notifications from the console.

But I want to send a notification from the server after a certain event is triggered. I followed the same approach as in GCM, but it doesn’t work.

05-20 20:40:58.941 30132-30919/com.google.firebase.quickstart.fcm E/AndroidRuntime: FATAL EXCEPTION: pool-1-thread-1 Process: com.google.firebase.quickstart.fcm, PID: 30132 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.messaging.RemoteMessage$Notification.getBody()' on a null object reference at com.google.firebase.quickstart.fcm.MyFirebaseMessagingService.onMessageReceived(MyFirebaseMessagingService.java:53) at com.google.firebase.messaging.FirebaseMessagingService.zzo(Unknown Source) at com.google.firebase.messaging.FirebaseMessagingService.zzn(Unknown Source) at com.google.firebase.messaging.FirebaseMessagingService.zzm(Unknown Source) at com.google.firebase.iid.zzb$2.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) at java.lang.Thread.run(Thread.java:818) 05-20 20:40:59.118 30132-30279/com.google.firebase.quickstart.fcm E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb9e83390 

Follow this PHP script to send a notification. If I try to execute the script, I get the following result.

 {"multicast_id":4679427854122301046,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1463757518309261%31bd1c96f9fd7ecd"}]} 

NOTE. I went through docs and changed the code to have only body and name. Even then it does not work.

+6
source share
7 answers

You can use this full code.

 <?php function sendFCM($mess,$id) { $url = 'https://fcm.googleapis.com/fcm/send'; $fields = array ( 'to' => $id, 'notification' => array ( "body" => $mess, "title" => "Title", "icon" => "myicon" ) ); $fields = json_encode ( $fields ); $headers = array ( 'Authorization: key=' . "AIzaSyA9vpL9OuX6moOYw-4n3YTSXpoSGQVGnyM", 'Content-Type: application/json' ); $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_POSTFIELDS, $fields ); $result = curl_exec ( $ch ); curl_close ( $ch ); } ?> 

Pass the message and token identifier as a parameter to call sendFCM($mess,$id) .

+8
source

I tried this and it worked:

 <?php $ch = curl_init("https://fcm.googleapis.com/fcm/send"); $header=array('Content-Type: application/json', "Authorization: key=GoGdfsflknEFñslknaglksjfnklj"); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false ); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "{ \"notification\": { \"title\": \"Test desde curl\", \"text\": \"Otra prueba\" }, \"to\" : \"SGferg-qWEFWbI:dflñkndfakllvakrgalkgjdgjslfkgjdglksdjflksjglkjlkñerhTHDFSHFZDHzdfakjsdhskjhgkjashfdasjdkf\"}"); curl_exec($ch); curl_close($ch); ?> 

This is the result:

 {"multicast_id":4913280949692448120,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1473389987003950%ab9a0bb6ab9a0bb6"}]} 
+4
source

To receive notification using remoteMessage.getNotification (). getBody () , you need to use a predefined set of keys for notification.

In this case, the key word is “notice” .

The JSON response should be formatted as follows.

  { "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...", "notification" : { "body" : "great match!", "title" : "Portugal vs. Denmark", "icon" : "myicon" } } 

You can also send notification information and data in the same JSON response

  { "to" : "APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...", "notification" : { "body" : "great match!", "title" : "Portugal vs. Denmark", "icon" : "myicon" }, "data" : { "Nick" : "Mario", "Room" : "PortugalVSDenmark" } } 

see this: https://firebase.google.com/docs/cloud-messaging/concept-options#messages-with-both-notification-and-data-payloads

+3
source

From php gist you send a message with data only. Your recipient expects a notification message, so when you receive a notification from a deleted message, it will be null, causing NPE to call getBody.

Send a notification and it should work properly. Notification requirements see here: https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support

+2
source

I ran into the same problem and after spending some time trying to figure out the reason, my observation was -

Since the notification field is a JSON representation of RemoteMessage.Notification . If you set any of the predefined fields of the Notification class to the "notification" field, on the client side the JSON is parsed successfully and you have a non-zero value for RemoteMessage.getNotification() , on which you can call getBody() / getTopic() / getIcon() .

But if you do not set any field of the Notification class to the json notification field, the parsing in the class will fail and you will have a zero value for RemoteMessage.getNotification()

So, any of the following three JSONs is the actual POST body for pressing RemoteMessage.Notification (in addition to the two examples shared by Andrea in the earlier answer), i.e. these three will not cause the aforementioned NPE

  { "to" : "<<FIREBASE_INSTANCE_ID>>", "notification" : { "body" : "Notification Message Body" } } { "to" : "<<FIREBASE_INSTANCE_ID>>", "notification" : { "title" : "Notification Title" } } { "to" : "<<FIREBASE_INSTANCE_ID>>", "notification" : { "icon" : "Notification icon" } } 

And none of the following three is valid for pushing RemoteMessage.Notification -

  • Does not have a notification field

     { "to" : "<<FIREBASE_INSTANCE_ID>>" } 
  • Notification field is empty json

     { "to" : "<<FIREBASE_INSTANCE_ID>>", "notification" : { } } 
  • There are several key value pairs in the notification field, but none of the fields defined in RemoteMessage.Notification class

     { "to" : "<<FIREBASE_INSTANCE_ID>>", "notification" : { "messageText" : "Notification Message Text", "messageBody" : "Notification Message Body" } } 
+2
source

 function send_fcm($tokens,$message) { $url = 'https://fcm.googleapis.com/fcm/send'; $priority="high"; $fields = array( 'registration_ids' =>$tokens, 'data' =>$message ); $headers = array( 'Authorization:key=your key', 'Content-Type: application/json' ); $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)); echo json_encode($fields); $result = curl_exec($ch); curl_error($ch); if ($result === FALSE) { die('Curl failed: ' . curl_error($ch)); } curl_close($ch); return $result; } 

store device identifiers in a token variable in array format

0
source

Try this code below, it will give a push notification for Android from the php server side, and you can get the device token from android, you need to go through dynamically to get a push notification for more Android devices.

 <?php function sendmessage_android($devicetoken,$message){ $api_key = 'AIzaSyCtDch9K3ZqGF_SSLYCz4JjMS4-fkJuW';//get the api key from FCM backend $url = 'https://fcm.googleapis.com/fcm/send'; $fields = array('registration_ids' => array($devicetoken));//get the device token from Android $headers = array( 'Authorization: key=' . $api_key,'Content-Type: application/json'); $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, 0); curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($fields) ); $result = curl_exec($ch); if(curl_errno($ch)){ return 'Curl error: ' . curl_error($ch); } curl_close($ch); $cur_message=json_decode($result); if($cur_message->success==1) return true; else return false; } ?> 
0
source

All Articles