Andorid FCM Integration

Now we'll create a simple app that receives Firebase messages from both Firebase console and from the J2ee code. First of all go to Firebase Console, create project and add a entry for Android project as shown in next Picture:


After creating Android project, download google-service.json:


Next step is add this google-service.json into your android app like in below image, see project struture:


Now make sure your app level build.gradle add below code:

buildscript {
    
    repositories {
        google()
        jcenter()
        
    }
    dependencies {
        ...
        // add below line
        classpath 'com.google.gms:google-services:4.3.3'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


Now add dependencies into you module level build.gradle as:

FCM Dependencies
apply plugin: 'com.android.application'
// make sure this plugin add into your build.gradle
apply plugin: 'com.google.gms.google-services'

android {
    ...
}

dependencies {
    ...
    // add below dependencies
    implementation 'com.google.firebase:firebase-messaging:20.1.7'
    implementation 'com.google.firebase:firebase-analytics:17.2.2'

    implementation 'com.android.volley:volley:1.1.1'
}


Now create MyFirebaseInstanceIdService.java where you will receive a new token if created. And you have to store it, it will use to send notification.

MyFirebaseInstanceIdService.java
package com.theitbulls.pushnotification.fcmservice;

import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;

public class MyFirebaseInstanceIdService extends FirebaseMessagingService {
    private static final String LOG_TAG = "MyFirebaseIdService";

    @Override
    public void onNewToken(String refreshedToken) {
        super.onNewToken(refreshedToken);

        Log.d(LOG_TAG, "Refreshed token: " + refreshedToken);
        storeToken(refreshedToken);
    }

    private void storeToken(String token) {
        SharedPrefManager
                .getInstance(getApplicationContext())
                .saveDeviceToken(token);
    }
}


Now create MyFirebaseMessagingService.java where you will receive notification information when received. Override onMessageReceived and you will get information as below:

MyFirebaseMessagingService.java
package com.theitbulls.pushnotification.fcmservice;

import android.app.NotificationChannel;
import android.app.NotificationManager;
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 com.theitbulls.pushnotification.R;

import java.util.Map;
import java.util.Set;

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String LOG_TAG = "FCMResult";
    private static final int NOTIFICATION_ID = 0x34;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        RemoteMessage.Notification notification = remoteMessage.getNotification();

        if (notification != null) {
            // for getting notification information
            String title = remoteMessage.getNotification().getTitle();
            String message = remoteMessage.getNotification().getBody();
            String icon = remoteMessage.getNotification().getIcon();

            Log.d("FCMMessage:", title + ": " + message + ": " + icon + ": " + remoteMessage.getData());
        }

        Map<String, String> data = remoteMessage.getData();
        if (!data.isEmpty()) {
            // for getting data notification information
            String result = "";
            Set<String> keys = data.keySet();
            for (String key : keys) {
                result += key + ":" + data.get(key) + ", ";
            }

            Log.d("FCMDataMessage:", result);
        }
    }
}


FCM notification complete example & result(of logcat) you can find below:

How to send Push Notification, below code snippet will tell you how?

public static void sendDataNotification(final Context mContext, JSONObject jsonData) {
    final ProgressDialog progressDialog = new ProgressDialog(mContext);
    progressDialog.setMessage("Sending FCM data notification...");
    progressDialog.show();

    String token = SharedPrefManager.getInstance(mContext).getDeviceTokenString();
    String url = BASE_URL + "?type=" + 1 + "&token=" + token;
    JsonObjectRequest jsonRequest = new JsonObjectRequest(url, jsonData, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            progressDialog.dismiss();

            String result = response.toString();
            Log.d("FCMStatus", result);
            DialogUtils.msgToast(mContext, result);
        }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                progressDialog.dismiss();

                Log.d("FCMError", error.toString());
                DialogUtils.msgToast(mContext, error.toString());
            }
        });

    VolleyInstance.getInstance(mContext).addToRequestQueue(jsonRequest);
}

How to send Data Notification, check below code:

public static void sendNotification(final Context mContext, final String title, final String msg) {
    final ProgressDialog progressDialog = new ProgressDialog(mContext);
    progressDialog.setMessage("Sending FCM Notification...");
    progressDialog.show();

    String token = SharedPrefManager.getInstance(mContext).getDeviceTokenString();
    String url = BASE_URL + "?type=" + 0 + "&token=" + token;
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        progressDialog.dismiss();
        try {
            JSONObject obj = new JSONObject(response);
            Log.d("FCMStatus", response);
            DialogUtils.msgToast(mContext, response);
        } catch (JSONException e) {
            Log.d("FCMError", e.toString());
            DialogUtils.msgToast(mContext, e.toString());
        }
    }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                progressDialog.dismiss();
                DialogUtils.msgToast(mContext, error.getMessage());
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();

                params.put("msg", msg);
                params.put("title", title);
                return params;
            }
        };

    addRetryPolicy(stringRequest);
    VolleyInstance.getInstance(mContext).addToRequestQueue(stringRequest);
}

After creating these two class, now you are ready to create notification, for Create or Manage Notification Click Here



Download: Android Complete FCM Project Here