Last updated on March 27th, 2020 at 06:57 pm

If you want to make your user activity in your Android application then firebase push notification plays an important role to keep your audience engaged in your application.

By sending a timely and relevant notification to your user you can re-engage your user to your app. Today there are no services available to send a notification but Firebase push notification is mostly used. In this post, I will teach you how we can implement firebase push notification in the android application.

What is the push notification?

A push notification is a message that shows in the notification bar of a mobile device. App publishers can send a notification at any time;  users will receive notification even if he was not using their devices. A publisher can share information like cricket score, coupons, latest news, etc in notification to engage the user.

Push notification is like SMS but the user needs to install your application from the play store to receive that notification. Most mobile OS like Android, iOS, Fire OS, Windows, and BlackBerry have there own push notification services.

What is the difference between an SMS and a push notification?

You can send and receive SMS from your android device. You can send a message to your contact 160 characters in length. But in case of a push notification, you need to install an app for example if you want news notification you need to install a news app after that you can receive a news notification in the notification bar.

What is Firebase Cloud Messaging (FCM)?

FCM is a cross-platform messaging service that allows you to send a notification to mobile devices at no cost.

Implementation of firebase push notification

Implementation of push notification is very easy, Go to firebase console and create a new project. Log in with your Google account.

Now you need to create a new project in the firebase console. Click on create a project button, name your project and press continue.

Firebase push notification android

In step 2 it will ask you to enable google analytics for this project in my case I don’t need this option so I disable it and click on create project button to continue.

Firebase push notification android

It will take some to ready your project once ready you can redirect to the dashboard.

Send FCM notification

Now you can click on Android Icon and add your project. If you already have a project in which you need to implement notification you can add the package name of your project when you register app.

Once you enter the package name register button activate click on the button.

Now you can download google-services.json file which we use in our application.

Now we open the android studio where we do remaining work. Open your project in Android studio first we add google-services.json file into our project.

Or you can drag-drop this file in an android studio inside the app folder. Now open project build.gradle and add google service dependencies classpath ''

Open app build.gradle file to add firebase dependencies in a project.

dependencies {
    /** Other library **/

    implementation ''
    implementation ''

apply plugin: ''

Now sync your project to install all added dependencies. Open AndroidManifest.xml file and add Internet permission to file.

<uses-permission android:name="android.permission.INTERNET" />

Create a new service file ( through which we can handle push notifications.

package com.firebasepushnotificationandroid;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;



import org.json.JSONException;
import org.json.JSONObject;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFcmListenerService";
    private NotificationManager notifManager;

    public void onMessageReceived(RemoteMessage remoteMessage) {

        // TODO(developer): Handle FCM messages here.
        // Not getting messages here? See why this may be:
        Log.e(TAG, "From: " + remoteMessage.getFrom());
        //createNotification("Hiii", this);
        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.e(TAG, "Message data payload: " + remoteMessage.getData());
            sendNotification(remoteMessage.getData().get("data"), this);

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

     * Create and show a simple notification containing the received FCM message.
     * @param messageBody FCM message body received.
    private void sendNotification(String messageBody, Context context) {
        Log.e("rsp", messageBody);

        String title = "Notification";
        String desciption = messageBody;

        Intent intent = null;

        try {
            JSONObject message = new JSONObject(messageBody);
            title = message.getString("title");
            desciption = message.getString("msg");
            intent = new Intent(this, MainActivity.class);
        } catch (JSONException e) {

        NotificationCompat.Builder builder = null;
        final int NOTIFY_ID = 0; // ID of notification
        String id = "mychannel"; // default_channel_id

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        if (notifManager == null) {
            notifManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = notifManager.getNotificationChannel(id);
            if (mChannel == null) {
                mChannel = new NotificationChannel(id, title, importance);
                mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});

            builder = new NotificationCompat.Builder(context, id)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
        } else {
            builder = new NotificationCompat.Builder(context, id);
            intent = new Intent(context, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    .setContentText(desciption)                            // required
                    .setSmallIcon(android.R.drawable.ic_popup_reminder)   // required
                    .setTicker("Accept your request")
                    .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})

        Notification notification =;
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        notificationManager.notify(NOTIFY_ID, notification);


You can add the above code in your file. Call this service file inside <application> in AndroidManifest.xml file

<service android:name=".MyFirebaseMessagingService">
        <action android:name="" />

Now open file in which we can generate FCM Id which is used to receive a notification.

        .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
            public void onComplete(@NonNull Task<InstanceIdResult> task) {
                if (!task.isSuccessful()) {
                    Log.w(TAG, "getInstanceId failed", task.getException());

                // Get new Instance ID token
                String token = task.getResult().getToken();

                // Log and toast
                String msg = token;
                Log.d(TAG, msg);

In the above code sendNotificationId() is used to upload the key to the server I am using OkHTTP 3 Library.

Sending push notifications from server

I am using PHP to send a notification to our mobile application. To send notification from the server first we need a server key that we can get from the firebase console. Go to Project Setting on click on setting icon then go to Cloud Messaging you can find your server key here.


Here is the PHP function which we use to send a notification to the device.


function sendMessage($data, $target, $serverKey){
    //FCM api URL
    $rsp = [];
    $url = '';
    //api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
    $server_key = $serverKey;
    $fields = array();
    $fields['data'] = $data;
            $fields['registration_ids'] = $target;
            $fields['to'] = $target;
    //header with content_type api key
    $headers = array(
    $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));
    $result = curl_exec($ch);
    if ($result === FALSE) {
        //die('FCM Send Error: ' . curl_error($ch));
    return $result;

You can see live examples of this code in this link here Firebase push notification android example. You can open this link and add your token and set your server key and message to your device.


Download complete Android and PHP code from below link

How to send push notification in android using firebase

  1. Go to firebase console open your project on the left menu under Grow click Cloud Messaging.
  2. Click on send your fist message.
  3. Fill required details and also add FCM Id which generates in android device and click publish.

And also don’t forget to subscribe to my youtube channel to provide you more informative tutorials. Thanks, happy coding.