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 TO SEND IMAGE IN PUSH NOTIFICATION ?

How does it work?

messaging-overview

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 4.1 or higher that also have the Google Play Store app installed, or an emulator running Android 4.1 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 {
         implementation 'com.google.firebase:firebase-messaging:17.3.4'
    }

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.
    <service android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
  • (Optional) Within the application component, metadata elements to set a default notification icon and color. Android uses these values whenever incoming messages do not explicitly set icon or color.
    <!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
         See README(https://goo.gl/l4GJaQ) for more. -->
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/ic_stat_ic_notification" />
    <!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
         notification message. See README(https://goo.gl/6BKBk7) for more. -->
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/colorAccent" />
  • (Optional) From Android 8.0 (API level 26) and higher, notification channels are supported and recommended. FCM provides a default notification channel with basic settings. If you prefer to create and use your own default channel, set default_notification_channel_id to the ID of your notification channel object as shown; FCM will use this value whenever incoming messages do not explicitly set a notification channel. To learn more, see Manage notification channels.
    <!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
         See README(https://goo.gl/l4GJaQ) for more. -->
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/ic_stat_ic_notification" />
    <!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
         notification message. See README(https://goo.gl/6BKBk7) for more. -->
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/colorAccent" />

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’s onCreate() 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 by extending FirebaseMessagingService and overriding onNewToken.
This section describes how to retrieve the token and how to monitor changes to the token. Because the token could be rotated after initial startup, you are strongly recommended to retrieve the latest updated registration token.

The registration token may change when:

  • The app deletes Instance ID
  • The app is restored on a new device
  • The user uninstalls/reinstall the app
  • The user clears app data.

Retrieve the current registration token

When you need to retrieve the current token, call FirebaseInstanceId.getInstance().getInstanceId()

Monitor token generation

the onNewToken callback fires whenever a new token is generated.

/**
 * Called if InstanceID token is updated. This may occur if the security of
 * the previous token had been compromised. Note that this is called when the InstanceID token
 * is initially generated so this is where you would retrieve the token.
 */
@Override
public void onNewToken(String token) {
    Log.d(TAG, "Refreshed token: " + token);

    // If you want to send messages to this application instance or
    // manage this apps subscriptions on the server side, send the
    // Instance ID token to your app server.
    sendRegistrationToServer(token);
}

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.

Prevent auto initialization

Firebase generates an Instance ID, which FCM uses to generate a registration token and Analytics uses for data collection. When an Instance ID is generated, the library will upload the identifier and configuration data to Firebase. If you prefer to prevent Instance ID autogeneration, disable auto initialization for FCM and Analytics (you must disable both) by adding these metadata values to your AndroidManifest.xml:

<meta-data
    android:name="firebase_messaging_auto_init_enabled"
    android:value="false" />
<meta-data
    android:name="firebase_analytics_collection_enabled"
    android:value="false" />

To re-enable FCM, make a runtime call:

FirebaseMessaging.getInstance().setAutoInitEnabled(true);

This value persists across app restarts once set.

Once the client app is set up, you are ready to start sending downstream messages with the Notifications composer.

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 the onMessageReceived 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:

<service
    android:name=".MyFirebaseMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

Override onMessageReceived

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

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // ...

    // TODO(developer): Handle FCM messages here.
    // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
    Log.d(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());

        if (/* Check if data needs to be processed by long running job */ true) {
            // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
            scheduleJob();
        } else {
            // Handle message within 10 seconds
            handleNow();
        }

    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }

    // 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.
}

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:

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

Background Restricted Apps (Android P or newer)

Starting Jan 2019, FCM will not deliver messages to apps which were put into background restriction by the user (such as via: Setting -> Apps and Notification -> [appname] -> Battery). Once your app is removed from background restriction, new messages to the app will be delivered as before. In order to prevent lost messages and other background restriction impacts, make sure to avoid bad behaviors listed by the Android vitals effort. These behaviors could lead to the Android device recommending to the user that your app be background restricted. Your app can check if it is background restricted using: isBackgroundRestricted().

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)

About the author

Akshay Raj

View all posts

162 Comments