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 …

firebase cloud messaging tutorial

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

[sociallocker id=1372] Firebase Cloud Messaging Source Code [/sociallocker]

Server Side PHP Code

[sociallocker id=1372] [download id=”3821″] [/sociallocker]

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 🙂

Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.

Expand Your Knowledge: Next Tutorial Picks

0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x