Android Push Notifications using Firebase Cloud Messaging (FCM), PHP and MySQL

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages and notifications at no cost.
Using FCM, you can notify a client app that new email or other data is available to sync. You can send notifications to drive user reengagement and retention. For use cases such as instant messaging, a message can transfer a payload of up to 4KB to a client app.


How does it work?


An FCM implementation includes an app server in your environment that interacts with FCM via HTTP or XMPP protocol, and a client app. Additionally, FCM includes the Notifications console, which you can use to send notifications to client apps.
Firebase Notifications is built on Firebase Cloud Messaging and shares the same FCM SDK for client development. For testing or for sending marketing or engagement messages with powerful built-in targeting and analytics, you can use Notifications. For deployments with more complex messaging requirements, FCM is the right choice.

Implementation path

Set up the FCM SDK Set up Firebase and FCM on your app according the setup instructions for your platform.
Develop your client app Add message handling, topic subscription logic, or other optional features to your client app. During the development, you can easily send test messages from the Notifications console.
Develop your app server Decide which server protocol(s) you want to use to interact with FCM, and add logic to authenticate, build send requests, handle response, and so on. Note that if you want to use upstream messaging from your client applications, you must use XMPP.

Set Up a Firebase Cloud Messaging Client App on Android

To write your Firebase Cloud Messaging Android client app, use the FirebaseMessaging API and Android Studio 1.4 or higher with Gradle. The instructions in this page assume that you have completed the steps for adding Firebase to your Android project.
FCM clients require devices running Android 2.3 or higher that also have the Google Play Store app installed, or an emulator running Android 2.3 with Google APIs. Note that you are not limited to deploying your Android apps through Google Play Store.

Set up Firebase and the FCM SDK

  1. If you haven’t already, add Firebase to your Android project.
  2. In Android Studio, add the FCM dependency to your app-level build.gradle file:
    dependencies {
         compile ''

Edit your app manifest

Add the following to your app’s manifest:

  • A service that extends FirebaseMessagingService. This is required if you want to do any message handling beyond receiving notifications on apps in the background. To receive notifications in foregrounded apps, to receive data payload, to send upstream messages, and so on, you must extend this service.
  • A service that extends FirebaseInstanceIdService to handle the creation, rotation, and updating of registration tokens. This is required for sending to specific devices or for creating device groups.
  • If FCM is critical to the Android app’s function, be sure to set android:minSdkVersion="8" or higher in the manifest. This ensures that the Android app cannot be installed in an environment in which it could not run properly.

For example:

        <action android:name=""/>
        <action android:name=""/>

Check for Google Play Services APK

Apps that rely on the Play Services SDK should always check the device for a compatible Google Play services APK before accessing Google Play services features. It is recommended to do this in two places: in the main activity’sonCreate() method, and in its onResume() method. The check in onCreate() ensures that the app can’t be used without a successful check. The check in onResume() ensures that if the user returns to the running app through some other means, such as through the back button, the check is still performed. If the device doesn’t have a compatible Google Play services APK, your app can call GooglePlayServicesUtil.getErrorDialog() to allow users to download the APK from the Google Play Store or enable it in the device’s system settings. For a code example, see Setting up Google Play Services.

Access the device registration token

On initial startup of your app, the FCM SDK generates a registration token for the client app instance. If you want to target single devices or create device groups, you’ll need to access this token.
You can access the token’s value by extending FirebaseInstanceIdService. Make sure you have added the service to your manifest, then call getToken in the context of onTokenRefresh, and log the value as shown:

public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);
    // TODO: Implement this method to send any registration to your app's servers.

The onTokenRefreshcallback fires whenever a new token is generated, so calling getToken in its context ensures that you are accessing a current, available registration token. FirebaseInstanceID.getToken() returns null if the token has not yet been generated.
After you’ve obtained the token, you can send it to your app server. See the Instance ID API reference for full detail on the API.
Once the client app is set up, you are ready to start sending downstream messages with the Firebase console.

Send a message from the Notifications console

  1. Install and run the app on the target devices.
  2. Open the Notifications tab of the Firebase console and select New Message.
  3. Enter message text.
  4. Select the message target. The dialog displays further options to refine the target based on whether you chooseApp/App Version, Device Language, or Users in Audience.

After you click Send Message, targeted client devices that have the app in the background receive the notification in the system notifications tray. When a user taps on the notification, the app launcher opens your app.

Receive and handle notifications

If you want to receive notifications when your app is in the foreground, you need to add some message handling logic in your client app.
To receive messages, use a service that extends FirebaseMessagingService. Your service should override theonMessageReceived callback, which is provided for most message types, with the following exceptions:

  • Notifications delivered when your app is in the background. In this case, the notification is delivered to the device’s system tray. A user tap on a notification opens the app launcher by default.
  • Messages with both notification and data payload. In this case, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.

If you want to open your app and perform a specific action other than the default action, set click_action as described below.
In summary:

App state Notification Data Both
Foreground onMessageReceived onMessageReceived onMessageReceived
Background System tray onMessageReceived Notification: system tray
Data: in extras of the intent.

For more information about message types, see Notifications and data messages.

Edit the app manifest

To use FirebaseMessagingService, you need to add the following in your app manifest:

        <action android:name=""/>

Override onMessageReceived

By overriding the method FirebaseMessagingService.onMessageReceived, you can perform actions based on the received message and get the message data:

public void onMessageReceived(RemoteMessage remoteMessage) {
    // TODO(developer): Handle FCM messages here.
    // If the application is in the foreground handle both data and notification messages here.
    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.
    Log.d(TAG, "From: " + remoteMessage.getFrom());
    Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());

Handle messages in a backgrounded app

When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.
This includes messages that contain both notification and data payload. In these cases, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.
If you want to open your app and perform a specific action, set click_action in the notification payload and map it to an intent filter in the Activity you want to launch. For example, set click_action to OPEN_ACTIVITY_1 to trigger an intent filter like the following:

  <action android:name="OPEN_ACTIVITY_1" />
  <category android:name="android.intent.category.DEFAULT" />

Advanced Messaging Options

Firebase Cloud Messaging (FCM) offers a broad range of messaging options and capabilities. To help you build an understanding of what you can do with FCM, this page lists and describes some of the most commonly used message options.
Many of these options are available only through the Firebase Cloud Messaging server implementation. For the full list of message options, see the reference information for your chosen connection server protocol, HTTP or XMPP.

How to find Firebase Api key ?

1- Go to Firebase Console.
2- Select your project.
3- Then go to Project Setting.
Screenshot (35)
Screenshot (36)
4- Click Cloud Messaging tab and Copy Server Key.
Screenshot (37)
Source Code Download

About the author

Akshay Raj

View all posts


Leave a Reply

Your email address will not be published. Required fields are marked *