Firebase Cloud Messaging for Android using PHP and MySQL

Hey guys, so here I am back with another Firebase Cloud Messaging tutorial. You all know about Firebase Cloud Messaging, it is a push notification service and we can use it to send messages to our app users.

This method is deprecated. Follow the updated tutorial here:
Android Push Notification Tutorial using Firebase Cloud Messaging

So here are the points that we are going to cover with this Firebase Cloud Messaging Tutorial.

Firebase Cloud Messaging for Android Video Series

  • If you want to go with a video tutorial explaining everything about Firebase Cloud Messaging then go through the below playlist.

Integrating Firebase Cloud Messaging in Android Project

Creating a new Android Project

  • With Android Studio 2.2 it is really easy to integrate firebase in your project.
  • First create a new Android Studio Project with an Empty Activity.
  • Once your project is loaded click on firebase from the tools menu.

firebase cloud messaging

  • After clicking on Firebase an assistant will open showing all the available firebase features.

integrating firebase cloud messaging

  • As you can see in the above images we have all the Firebase Services. But at this time we care about Cloud Messaging. So click on Cloud Messaging. 

Setting Up Firebase Cloud Messaging

  • You will see a link saying Set Up Firebase Cloud Messaging. Click on it.

set up firebase cloud messaging

  • Now you will see all the steps required to Set up Firebase Cloud Messaging in the project.

firebase cloud messaging tutorial

#1 Connect Your App to Firebase

  • Simply click on the Connect to Firebase button. It will start a connect dialog.
  • Here you can create a new Project on Firebase, as I am creating a project named FcmSimplifiedCoding (See the below screenshot). Or you can also select an existing firebase project.

connect to firebase project

  • Now simply click on Connect to Firebase. And wait for a few seconds. And you will see the following message in the assistant.

connect your app to firebase

  • So step number 1 is completed successfully. Now lets move ahead.

#2 Add FCM to Your App

  • Again click on the button Add FCM to your app and you will see a dialog box.

add fcm

  • Click on Accept Changes. And firebase is setup in your project now.

Generating Device Token

  • Every device generates a unique token to receive notifications. And for this we have to create a class that will extend the class FirebaseInstanceIdService. This part is same as we did in the previous Firebase Cloud Messaging Tutorial.
  • So create a class named MyFirebaseInstanceIDService.java and write the following code.

  • As this is a service we need to define this class inside AndroidManifest.xml. So come inside AndroidManifest.xml and write the following code inside application tag.

Storing Device Token

Saving Token

  • First we will store the generated token in SharedPreferences.
  • So, for managing the SharedPreferences we will create a class in Singleton Pattern.
  • Create a class named SharedPrefManager.java and write the following code.

  • Now to save the token generated with the FirebaseInstanceIdService we will call the method of the above class.
  • So you need to modify the class MyFirebaseInstanceIDService.java as below.

Displaying Token

  • Though this part is not necessary but just to make sure the token is generated and saved in the SharedPreferences, we can display the token.
  • For this come inside activity_main.xml and write the following code.

  • The above code will generate the following layout.

firebase cloud messaging fcm

  • We have a Button and a TextView. On button click we have to display the token on the TextView. We can easily do it by using the Singleton class SharedPrefManager that we created.
  • So come inside MainActivity.java and write the following code.

  • Now just run your application. And click on the button you should see the token in the TextView.

firebase cloud messaging

  • But if you are seeing token not generated then something is wrong. In this case try with a different emulator. Or try by uninstalling the application from your device.
  • If you are getting the token, then you can move ahead.

Creating Messaging Service

  • We have the device token, now we need one more class that will extend FirebaseMessagingService, this class will actually receive the notification.
  • So create a new class named MyFirebaseMessagingService.java and write the following code.

  • In the above code onMessageReceived(RemoteMessage remoteMessage) method will be called when the message is received by the push notification.
  • Again we need to define this service inside AndroidManifest.xml. For this write the following xml code inside <application> tag.

  • Now we need to handle the message that will be received, to display it as a notification.

Displaying Push Notification

Creating a class to Handle Push Notifications

  • To show push notification we will create a class named MyNotificationManager.java. Here we will create the required method to show the notifications.

  • We will be using the methods showBigNotification() and showSmallNotification() to notify the user as required.
  • These methods will be called from the MyFirebaseMessagingService.java class. So lets modify this class to display notification.

Displaying Notification

  • Come inside MyFirebaseMessagingService.java and modify it as below.

  • We have done with the notification, but a very important thing still remaining. We have to store the token to the server. As by now, the device token is in the device only and without token we cannot use Firebase Cloud Messaging. So here comes that task of creating the web services that will store the registration token to our server.

Building Web Services Part 1

  • In this phase we have to do the following tasks.
    • Database Creation
    • Web service to store token in database
  • I will be using XAMPP, using PHP is not necessary you can use any technology you are comfortable in. I am using PHP with XAMPP. So lets start with Database Creation.

Creating Database

  • Go to phpmyadmin and run the following SQL command to make the database.

  • We will insert an email and device token in each row of the table. So lets move into creating php scripts.

Creating PHP Scripts

Scripts for DB Connection and DB Operation

  • Again I will be doing this thing in the simplest way but in real world scenario you should follow Creating RESTful API for these tasks.
  • Inside the directory htdocs (because I am using xampp) create a folder for the php scripts. I created FcmExample.
  • Inside FcmExample create a file named Config.php and write the following code.

  • Create a file named DbConnect.php, in this file we will create a class to connect to our database.

  • Now create another file named DbOperation.php, in this file we will create a class to handle the database operations.

Script to Store Device Token in MySQL

  • To store the token to database we need one more script that will actually get the token and process it to the database. So create one more php file named RegisterDevice.php.

  • Now test the script using a REST Client. I am using POSTMAN here.

firebase cloud messaging

  • As you can see the script is working fine. But before moving ahead in Android side you need to use the host ip instead of localhost in the URL.
  • For windows use ipconfig in command prompt and in terminal use ifconfig to know the IP Address. So in my case the URL to this script with the ip is.

http://192.168.1.102/FcmExample/RegisterDevice.php

Script to Fetch All the Registered Device

  • As we will send the push from the android device itself. So we need to get all the registered device. For this task we need a php script that will fetch all the registered device from database.
  • So create a file named GetRegisteredDevices.php and write the following code.

  • You can check this script as well.

firebase cloud messaging fcm

 

Storing Token to MySQL Database

  • Now we send the token from SharedPreference to MySQL database. As our web service for this action is ready.
  • First we will modify the activity_main.xml as below.

  • Now we have the layout for MainActivity as below.

register device fcm

  • So we have an EditText and a Button. We need to put email in the EditText then click on the Button to register the device for receiving notification.
  • Now to complete the functionality made the following changes in MainActivity.java.

  • After this you can try running your application.

firebase cloud messaging

  • As you can see we are getting the success message. Now check the MySQL database to ensure that token is stored.

mysql fcm token

  • Yeah we got the device token in our MySQL database.

Building Web Services Part 2

  • Again we need to build some more web services. So lets begin.

Building Web Service for Sending Push Notification

  • Now we will build the Web Service needed to send push notification.
  • We have two kinds of push notification in this project. One when we will send Push to a single device. And the other one is when we will broadcast push notification to all devices.
  • But first we will configure some basic things for sending push using Firebase Cloud Messaging.

Getting Firebase Server Key

  • Go to Firebase Console and inside your project settings go to cloud messaging tab.
  • You will find the Cloud Messaging Server Key here, copy it.

fcm server key

  • Now go inside the existing Config.php file and define one more constant that will store our Firebase API Key.

Creating a class to store Push Notification

  • Create a file named Push.php and write the following code.

  • The above class is very simple its only initializing the variables required for push in the constructor, and giving us back an array with the required data in getPush() method.

Creating a Separate Class for Handling cURL operation

  • To send push notification we need to make http request to firebase server. And we can do it using cURL. So to handle this task create a new php file named Firebase.php and write the following code.

Script to Send Push Notification

Sending to a Single Device
  • To send push to a single device create a php script named sendSinglePush.php and write the following code.

  • Now again you can test this script using POSTMAN.
  • First try sending a notification without image. So we have to put only title, message and email in parameters.

fcm without image

  • If you are getting a success then you should see the notification in your device as well.
firebase cloud messaging push notification
Firebase Cloud Messaging
  • Now also try notification with an image. To send an image along with the message you just need to put one more parameter in the request named image and it will contain the url of the image.

firebase cloud messaging with image

  • In this time you should see a notification as below in the device.
firebase cloud messaging push with image
  • So the push notification is working absolutely fine.
Sending to All Device
  • Now the second case is when we want to broadcast message to all the register device. For this create one more php script named sendMultiplePush.php and write the following code.

  • Thats it for the server side coding. Now lets move in Android Studio again to finish our app.

Making Send Notification Option in App

  • The first thing we will do is create a separate class for storing all the URLs required. So create a class named EndPoints.java and write the following code.

  • Now we will create a send notification option for our application. So again come inside activity_main.xml.

  • We added one more button and this button will take us to another activity from where we can send push notification to devices.

Creating Activity For Sending Push Notification

  • Now create another EmptyActivity named ActivitySendPushNotification.
  • For this activity we will create the following layout.
firebase cloud messaging tutorial
Firebase Cloud Messaging Tutorial
  • We have a Radio Button group for individual or multiple push option. Then a Spinner to display registered devices. Three EditTexts for title, message and image url.
  • For the above layout here is the xml code.

  • Now the first thing we will do is we will modify the MainActivity.java to open this activity on button click.

Creating a Volley Singleton Class

  • As we need to perform http request several time that is why, we are defining a singleton pattern for volley to handle network requests.
  • Create a class named MyVolley.java and write the following code.

  • Now we will code the ActivitySendPushNotification.java, so come inside the class.
  • First define the views and all the required methods.

  • Now we have to load the registered devices to the spinner. We already have the webservice to fetch devices.

Fetching All Devices

  • Write the following codes in the method loadRegisteredDevices() 

  • If you will run the application now you will see the emails in the spinner.

firebase cloud messaging push

Sending Push Notification

  • Now the last part of this Firebase Cloud Messaging Tutorial and the main thing, sending push notification to the devices.
  • So now we will code the remaining methods.
  • First inside the method sendPush() write the following code.

Sending to A Single Device
  • Write the following code in method sendSinglePush() for sending to a single device that is selected from the spinner.

  • Now you can test the application for single push as well.

firebase cloud messaging fcm push

  • Now lest code the last method of this Firebase Cloud Messaging Tutorial which is about sending multiple push notification.
Sending to Multiple Device
  • Write the following code for sendMultiplePush().

  • Now thats it. You just need multiple emulators now to test the application.

fcm push notification

  • Bingo! Notifications are working absolutely fine.
  • Now if you want the source code of the application you can get it from below.

Firebase Cloud Messaging Source Code

Android Side Source Code

Server Side PHP Code

So it is the end of Firebase Cloud Messaging Tutorial. This is the longest tutorial so far, and if you want to make this Firebase Cloud Messaging Tutorial work, have patience and follow the whole tutorial carefully.And yes if you have some confusions regarding this Firebase Cloud Messaging Tutorial. Lets meet in comment section. Also share this tutorial among your friends. Thank You 🙂

178 thoughts on “Firebase Cloud Messaging for Android using PHP and MySQL”

      • Dud This is Really Nice Tutorial…..
        But I am Getting following Tpe of Error in My Device

        Unauthorized

        Unauthorized
        Error 401

        []

        Please Help Me With this….
        How to solved It???????
        Reply Me….

        Reply
        • I think you are using legacy server key…..instead of using it use server key which you will find in firebase console overview->project settings->cloud messaging…i was also having the same problem but after changing…..it worked….hope it may work in your case also….

          Reply
      • Hello ,i found your code so insightful and helpful,am able to send notification from local host but when i connect it to remote remote server,it fails to function as expected,what might be the problem?

        Reply
  1. Hi, I installed the demo apk and registered sucessfully. I selected push and entered all the details and clicked on push. But i didnt receive any push. Is there anything which I need to setup ?

    Reply
  2. Hi Belal,

    Great Tutorial. But I need you your help. B’coz i’m getting “volley timeout exception” error. I followed all steps as you mention. Please reply ASAP.

    Reply
  3. Belal!
    I’ve followed every step but while testing PHP scripts, I got an error:
    Fatal error: Call to undefined method mysqli_stmt::get_result() in DBOperation.php

    I’ve searched and tried few options from stackoverflow but nothing really worked for me.

    P.S: I’ve uploaded these scripts to Hostgator cPanel.
    P.P.S: I’m very beginner in PHP.

    Reply
    • Ola, para mim funcionou assim:

      //getting all tokens to send push to all devices
      public function getAllTokens(){

      // $stmt = $//this->con->prepare(“SELECT token FROM devices”);
      // $stmt->execute();
      // $result = $stmt->get_result();
      $result = $this->con->query(“SELECT token FROM devices”);
      $tokens = array();
      while($token = $result->fetch_assoc()){
      array_push($tokens, $token[‘token’]);
      }
      return $tokens;
      }

      //getting a specified token to send push to selected device
      public function getTokenByEmail($email){
      $stmt = $this->con->query(“SELECT token FROM devices WHERE email = ?”);
      //$stmt->bind_param(“s”,$email);
      //$stmt->execute();
      //result = $stmt->get_result()->fetch_assoc();
      return array($stmt[‘token’]);
      }

      //getting all the registered devices from database
      public function getAllDevices(){
      $stmt = $this->con->query(“SELECT * FROM devices”);
      //$stmt->execute();
      //$result = $stmt->get_result();
      return $stmt;
      }
      }

      Reply
  4. Thanks for the tutorial its awsome, I would like to tell you one point is that replace Constants.php to Config.php in Dbconnect.php file, it may create problem for some freshers

    Reply
  5. protected Map getParams() throws AuthFailureError {
    Map params = new HashMap();
    params.put(“title”, title);
    params.put(“message”, message);

    if (!TextUtils.isEmpty(image))
    params.put(“image”, image);

    params.put(“email”, email);
    return params;
    }
    error in MAP , it said params incompatble return type in volly.request,or import class of map

    Reply
  6. Curl failed: Failed connect to fcm.googleapis.com:443; Operation now in progress, I tried many times but it gives me the same error

    Reply
  7. Thanks for the tutorial….
    Will you please help me to get notification when is no longer is background or in foreground state…

    Thanks in advance.

    Reply
  8. hi there thank you for the article ….Please can you help me i have more than 1000 token so i want to push my notification to my user but how can i do that using php i have been doing trying but bacthing theses users in to 1000 each then send it seems to be a challange really

    Reply
  9. Hello. How to send several notifications at one time, when I send a new notification without opening old, it just replaces old notification, not updates it.

    Reply
  10. Hie, Can you help me i tried to follow your and implement your code, but i am getting the following error
    Error:(33, 28) error: cannot find symbol variable SharedPrefManager

    Reply
  11. hi bro,

    i’m yashwanth, i’m new to android.

    i followed your code, and i’m getting these output in RegisterDevice.php

    {“error”:true,”message”:”Invalid Request…”}

    But u r showing something else in screeshot.

    can you help me.

    can any one help me please

    Reply
    • if you used postman for testing like this tutorial, change method from ‘get’ to become ‘post’ at left side address bar.

      Reply
  12. hi bro,

    i’m yashwanth, i’m new to android.

    i followed your code, and i’m getting a black spot while registering device on to server

    can you help me??

    can any one help me please???

    Reply
  13. How to create this notification Responsive ?? Mean on notification received, i want to response again in Accept or Reject form to that user, from which i received.

    Reply
  14. Thanks alot man, it worked. What if I have application A and Application B. Application A will send notification to Application B and when user clicked the notification, the Application B will be opened.

    Reply
  15. Heello when i try to send 192.168.1.102:9090/FcmExample/sendSinglePush.php on postman i had
    {“multicast_id”:9209621789040171387,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]}[]
    Pls helpppp !!!!!!!!

    Reply
  16. hi belal! i got this working fine…

    Now when a user uninstall the app and again reinstall the app he is not able to get notification…. what will be the solution???

    Thank you..

    Reply
  17. Sir I have two Question . 1) how i will set TTL(time to live) for notification
    2) how i will get the Sender id in notification, because after receiving notification i want to send back the notification to that user.

    Reply
  18. hi, thanks for tutorial. I already follow all that you mentioned in your tutorial and get a response when I try with Postman and the results in accordance with your screenshots, but the problem is the notification did not appear on my android device. can you help…,a little code i’m doing
    index.php
    $app->post(‘/sendpush’, ‘authenticate’, function() use ($app) {
    // check for required params
    global $user_id;
    verifyRequiredParams(array(‘title’,’message’,’group_id’));
    $response = array();
    $title = $app->request->post(‘title’);
    $data = $app->request->post(‘message’);
    $group_id = $app->request->post(‘group_id’);
    //getting the token from database object
    $db = new DbHandler();
    $registration_ids = $db->getAllTokens($group_id, $user_id);
    if ($registration_ids) {
    $push = new Push($title, $data);
    $mPushNotification = $push->getPush();
    //var_dump($title);
    $fb = new Firebase();
    echo $fb->sendMultiple($registration_ids, $mPushNotification);
    //var_dump($registration_ids);
    echo json_encode($response);
    }
    echoRespnse(200, $response);
    });
    DbHandler.php
    //getting all tokens to send push to all devices
    public function getAllTokens($group_id, $user_id){
    $stmt = $this->conn->prepare(“SELECT mst_users.token FROM mst_group INNER JOIN
    group_member ON group_member.group_id = mst_group.id
    INNER JOIN mst_users ON group_member.user_id = mst_users.id
    WHERE mst_group.id = ? AND mst_users.id ?”);
    $stmt->bind_param(“ii”, $group_id, $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $stmt->close();
    $tokens = array();
    while($token = $result->fetch_assoc()){
    array_push($tokens, $token[‘token’]);
    }
    return $tokens;
    }
    push.php
    title = $title;
    $this->message = $message;
    }
    //getting the push notification
    public function getPush() {
    $res = array();
    $res[‘data’][‘title’] = $this->title;
    $res[‘data’][‘message’] = $this->message;
    return $res;
    }
    }

    Reply
  19. I have try your each step at least 4-5 time but still it issue “token not generated” . i have clear catch , uninstall also make new genymotion emulator but i have not solve problem.

    Reply
      • Dear Belal
        Few Questions Arises To Many Developers including me .Please Have some Solutions for these Such as:

        {“multicast_id”:9209621789040171387,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]}[]

        Alternative For This Instead of local server
        Fatal error: Call to undefined method mysqli_stmt::get_result() in DBOperation.php

        Reply
        • Did u got any solution for {“multicast_id”:7912757118272451652,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]}[]
          Plzz Help i also want solution of this…

          Reply
  20. Fatal error: Call to undefined method mysqli_stmt::get_result() in C:\xampp\htdocs\FcmExample\DbOperation.php on line 71
    how to resolve this problem?

    Reply
  21. Hi SIr,Thank you so much for this wonderful tutorila.I have one question.How to fix ,a registered user again subscribe with the same email id after clear data .He gets the message”Device already registered” but in databse the old token remain same so the device doesnt get push notification.I am stucked with DbOperation file.Please help me to fix this.

    Kind Regards,
    Madhusudan

    Reply
  22. Here is my code of DbOperation.php where I am trying to update token when an email id exist.
    public function addRegistrationToekn($token,$email){
    $stmt = $this->con->prepare(“UPDATE devices SET token=? WHERE email=?”);
    $stmt->bind_param(“si”,$token,$email);
    $result = $stmt->execute();
    $stmt->close();
    if($result){
    return false;
    }
    return true;
    }

    And for this I tried to update RegisterDevice.php
    Please help me where I am doing mistakes

    registerDevice($email,$token);
    $result1=$db->addRegistrationToekn($token,$email);

    if($result == 0){
    $response[‘error’] = false;
    $response[‘message’] = ‘Device registered successfully’;
    }elseif($result == 2)
    {
    if($result1==false)
    {
    $response[‘error’]=false;
    $response[‘message’]=’Device updated with token’;
    }
    else{$response[‘error’]=true;
    $response[‘message’]=’Device updation failed’;
    }
    }
    else{
    $response[‘error’]=true;
    $response[‘message’]=’Invalid Request…’;
    }
    }

    echo json_encode($response);

    Reply
  23. hey Belal evrything is working Fine

    But the only thing which is not working is while sending the message !!

    When we click on Send Push Button we get this error!!

    {“multicast_id”:9209621789040171387,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]}[]

    And many of us are facing the same error!!

    Would be great if you tel us how to resolve this 🙂

    Waiting!!

    Reply
  24. Hi Sir ,Thank you for this tutorila. I have a doubt.
    If I send a notification and the application is starting or in the background, everything works correctly, but if the application is stopped / killer no notifications arrive. Whatsapp or gmail do it and I do not know how do it!!!

    Reply
  25. GEtting this error,

    Error:(22, 26) error: cannot access AbstractSafeParcelable
    class file for com.google.android.gms.common.internal.safeparcel.AbstractSafeParcelable not found

    pls help

    Reply
  26. Can someone please scale this to have users (profiles)
    and login/register/forgot password
    messages stored in the database too

    would be amazing

    Reply
  27. $fields = array(
    ‘registration_ids’ => $registration_ids,
    ‘data’ => $message,
    );
    this should be like below
    $fields = array(
    ‘to’ => $registration_ids,
    ‘data’ => $message,
    );

    Reply
  28. I love this tutorial but you server code fails to address very critical concerns.

    1. the device token can change after app install I believe. What happens when you try to register the new token and email is you get user already registered and you are left with an old token that doesn’t work.
    2. what if the user logs in using two devices or abandoned his old device for a new one? Using the same code you will get the same error that user already registered even in a different device.

    if you have time in your schedule you can check and try to update server-side code, please.
    Cheeers.

    Reply
  29. Response for “send multiple push” method is to add header content length after adding content length using getheader(), response is “missing parameter” from scripting files, please provide solution for it.Values are sent correctly from app , don’t know where they are missing.

    Reply
  30. Connected Succsfully…{“multicast_id”:7300338169869987506,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]}[]

    Reply
  31. I need to implement the same tutorial in eclipse IDE . Is it possible ? If yes , please mention the things i want to do manually . (For example : i have created jar files and put it in the libs folder , which really worked and cleared errors . How ever the token is not generating. Do i want to do anything with the google-services.json file , which i downloaded from the firebase console of my project)

    Reply
  32. Eu fiz o exemplo e funcionaol até a parte de salvar no banco. Mas quando seleciono a spinner não funcional! Alguém consiguio fazer? Selecionar a spinner e mostrar os e-mails? Tô fazendo usando servidor externo da Hosting!

    Reply
  33. Hi Belal
    How to slove this problem
    {“multicast_id”:9209621789040171387,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]}[] .

    Reply
    • Means you no data was received by the server. Change POSTMAN to POST don’t use GET or ensure you’ve posted data through the URL

      Reply
  34. Can u please help its saying this error.

    Unauthorized

    Unauthorized
    Error 401

    []
    in Server Page And Following Show in Device

    Unauthorized

    Unauthorized
    Error 401

    []
    How to Fixed It…..Please Help Me….

    Reply
  35. I always get HTTP 500 error when i get results from GetRegisteredDevices.php
    (But I can add a device to DB)

    I couldn’t fix it. It’s an online server, not local and i will use this online.
    How can i do now? Thanks.

    Reply
  36. Dear Sir,
    (1) Notification using FCM,php error but notification not display on device/emulator
    (2) instead of mysqli_xx() can i use only mysql_xx() because i used to wamp

    Reply
  37. thanx for tutorial can u please tell how to vibrate mobile on push notification any idea…

    “notification”:{
    “sound”:”default”
    }

    Reply
  38. Hi Belal Khan a lot of thanks!!!! you just saved my day….but there is one request can you please upload the video tutorial of this entire project as i am a fresher i want to understand it indepth (i.e. specially php part as i am completely new to it) i’ve implemented it but still ….it’s a humble request…and thank you once again….

    Reply
  39. Hey Dear! this tutorial is awesome but php file not working on live its only working on local server. You used old php function please can you update these functions.
    There is problem in dbOperation class. I am unable to fetch all email only register is working on live server. My Live server has no MySQLnd driver.
    Please can anyone help am waiting for good response. Thank You

    Reply
    • Use this way to fetch tokens

      public function getAllTokens(){
      $stmt = $this->con->prepare(“SELECT token FROM devices”);
      $stmt->execute();
      $stmt->bind_result($token);
      $tokens = array();
      while($stmt->fetch()){
      array_push($tokens, $token);
      }
      return $tokens;
      }

      Reply
      • this is also not working dear..
        now devices are not registering and fetching . latest errors

        [21-Mar-2017 06:47:31 America/Chicago] PHP Parse error: syntax error, unexpected ‘token’ (T_STRING) in /home/comsolne/public_html/FcmExample/DbOperation.php on line 58
        [21-Mar-2017 06:47:35 America/Chicago] PHP Parse error: syntax error, unexpected ‘token’ (T_STRING) in /home/comsolne/public_html/FcmExample/DbOperation.php on line 58

        please can you mail me all latest php code which can work on live server my email address is
        zeeshanarif34@gmail.com

        Reply
  40. Assalamualaikum Belal, i have a problem like this ..
    Fatal error: Call to undefined method mysqli_stmt::get_result() in C:\xampp\htdocs\FcmExample\DbOperation.php on line 50
    how to resolve this problem?

    Reply
  41. {“multicast_id”:9209621789040171387,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]}[]

    For the users who are having this issues please use the correct email which you specified on the register device section of the app and you will successfully send the message, however I cant go on further because I’m having a crash right afterwards with myfirebaseinstance….

    Reply
  42. hey Belal .. I want to send a notification to a single device when a new a new record is added to the database how can I achieve this?

    Reply
    • there is two radio button one for send to many and other for send to one.. now go to spinner and select desire email where you want to send.

      Reply
    • Hey Sara. You could use a mySQL trigger for this. You could also tell your android device to call another URL i.e for sending the Push notification once it has stored the new record in your database. You could also introduce curl in your php code for inserting a record into the database such that after storing the record, it also sends a push notification

      Reply
  43. Thank you so much for the detailed and clear tutorial, I managed to make Firebase app with this where users are able to go into a chat room and send messages. BUT i have a problem where when a user press send to send a message, all users who’s got the app receive the notification even if there not in the chat room. can you please show us or make a tutorial on how to send push notification to some certain numbers of users who has commented in a chat room? please am other people might need this as well thanks.

    Reply
  44. In my real device, i get the refresh token successfully then after a moment it disappears, and the logs never stop scrolling, hence the token never gets stored to server…i don’t know why and how this is happening. On both genymotion and android studio emulator everything works as expected. please help?

    Reply
  45. I am getting Mismatch sender Id error. Please help me to solve this issue.
    {“multicast_id”:6245778731055199638,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”MismatchSenderId”}]}[]

    Reply
  46. I am getting this error.Please help me to solve this error.
    {“multicast_id”:8388467262669440974,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”MismatchSenderId”}]}[]

    Reply
    • Please solve this Error.

      {“multicast_id”:7300338169869987506,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]}[]

      Reply
    • Add a parameter to your messages you’re sending to firebase with the username. Check when a message comes through for the authorizing username and if they are similar, don’t display. If they are not similar, send the data to display the message and remove the username part from your string.

      Reply
  47. Thanks belal for this tutorial….it’s too much easy to understand…hope you’ll adding tutorial’s like this in near future…for developer like us…..once again thanks a lot….

    Reply
  48. sendUserActionEvent() mView == null
    I getting this error when clicked register device. Could you please help me ?

    Reply
  49. Inactivity, disconnecting from the service
    Hello, I also get this error. Could you please help me why I am getting this ?

    Reply
  50. {“multicast_id”:9209621789040171387,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]}[]

    Your Hosting does’nt have MYSQLND. try with https://in.000webhost.com/ it is free hosting

    Reply
  51. I have successfully done folloed your tutorial. But if I do build apk and install to my phone, this app can’t register token, can’t send notification and can’t get any notification. ???

    Reply
  52. Does this just work on emulator or also on my phone?
    Because i can’t set the token into the textview on my phone…
    However Logcat says that the file isn’t found in data/users/0/MYAPLLICATIONNAME/ etc.
    Can you give me a short hint what I’m doing wrong?
    Thanks alot.

    Reply
  53. Hello Mr belal do you know how to make an android application that automatically receives notification when it checks in mysql database and finds that there is a new entry in the table..

    Reply
  54. Hello, i am getting the following error in

    Failed to connect to MySQL: Unknown database ‘fcm'{“error”:true,”message”:”Parameters missing”}

    Please Help !

    Reply
  55. Thanks for this tutorial .I have error, Token not generated. I uninstalled application and tried again but still error did not solve . please help me how to solve it

    Reply
  56. It is sending the message . But the message is not being received on the device to which the message has to be sent.
    The toast when Send to one device is showing : {“multicast_id”: 789070…, “success”:1 , “failure”: 0 ,”canonical_ids”:0,”results”:[{“message_id”:”2398043094….”}]}[]

    Reply
  57. Very nice Tutorial.. Thank you so much

    I have on error , when i click on send push button that time throws error on my application :-

    The request was missing an Authentification Key (FCM Token). Please, refer to section "Authentification" of the FCM documentation, at https://firebase.google.com/docs/cloud-messaging/server.

    The request was missing an Authentification Key (FCM Token). Please, refer to section "Authentification" of the FCM documentation, at https://firebase.google.com/docs/cloud-messaging/server.
    Error 401

    error in console –
    W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
    E/EGL_emulation: tid 3553: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH)
    W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x977c6640, error=EGL_BAD_MATCH

    please help sir, how to solve this error and explain in brief how to modify my answer….
    Thank you so much…………………….

    Reply
  58. Thanks for your tutorial..But My App is not receiving push notification if i remove app from all task(task manager)..Please help me how to solve it

    Reply
  59. Hi
    Thanks for your useful tutorial.
    I implement that it is working , i can get notification in some devices but i can not get in some other devices. POST send get back success but notification not received.
    this problem lost more than 1 week of my time.
    please help me.

    Reply
  60. First, Thank you for this tutorial.
    But i face issue when app is in foreground i am not able to receive notification, i receive application when app in background.

    Thanks for your help.