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 'com.google.gms:google-services:4.3.2'

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

dependencies {
    /** Other library **/

    implementation 'com.google.firebase:firebase-messaging:17.4.0'
    implementation 'com.google.firebase:firebase-core:16.0.1'
}

apply plugin: 'com.google.gms.google-services'

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 (MyFirebaseMessagingService.java) through which we can handle push notifications.

package com.firebasepushnotificationandroid;


import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

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


public class MyFirebaseMessagingService extends FirebaseMessagingService {

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

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        // TODO(developer): Handle FCM messages here.
        // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
        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);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        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,
                PendingIntent.FLAG_ONE_SHOT);

        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.enableVibration(true);
                mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                notifManager.createNotificationChannel(mChannel);
            }

            builder = new NotificationCompat.Builder(context, id)
                    .setContentTitle(title)
                    .setContentText(desciption)
                    .setContentIntent(pendingIntent)
                    .setSound(defaultSoundUri)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT);
        } 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);
            builder.setContentTitle(title)
                    .setContentText(desciption)                            // required
                    .setSmallIcon(android.R.drawable.ic_popup_reminder)   // required
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)
                    .setTicker("Accept your request")
                    .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
                    .setPriority(Notification.PRIORITY_HIGH);
        }

        Notification notification = builder.build();
        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">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

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

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

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

                // Log and toast
                String msg = token;
                Log.d(TAG, msg);
                sendNotificationId(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.

<?php

function sendMessage($data, $target, $serverKey){
    //FCM api URL
    $rsp = [];
    $url = 'https://fcm.googleapis.com/fcm/send';
    //api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
    $server_key = $serverKey;
    $fields = array();
    $fields['data'] = $data;
    if(is_array($target)){
            $fields['registration_ids'] = $target;
        }else{
            $fields['to'] = $target;
    }
    //header with content_type api key
    $headers = array(
        'Content-Type:application/json',
        'Authorization:key='.$server_key
    );
    
    $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));
    }
    curl_close($ch);
    
    //print_r($result);
    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.