In this post, I will explain how to add push notification feature in your android app, I see a lot of tutorial on firebase push notification but they are sending notification from firebase console, not from android app. So today, I will create app to app firebase android notification. In which user can send notification from android device not firebase console to specific android device.





We will be using retrofit library in android which help you to do http request and callback, so you can retrieve data from online firebase with few line of code.




Firebase has already build in feature of push notification, you need to do is add firebase could messaging dependency in android gradle and sync the project to download library.





First I will talk on what is concept of firebase push notification then I will discussed on practical example of firebase push notification. So in the firebase push there are two things Notification model and Data model, Notification model carries data a notification while Data model carries normal data that can be used for intent, sqlite database and many other operation. Why notification model or Data model is separated, because in firebase when is in background, you can not use data model unless your app is in foreground therefore, notification model is separated and it is automatically used when your app is in background, create auto notification and taking data from notification model. You will be confused now with notification model or data model but later in practical example it is cleared in coding.



See in the above picture, there are two app state, in which firebase push notification work differently in these two app state, one is foreground app state and other is background app state. According to documentation, when your app is in foreground state then you will get both notification data and payload data, similarly when app is in background state, only notification data will be delivered. There is special way to handle firebase push notification when your app is in background state. I will explain further in code (practical implementation).


Last thing to clarify is token, well in this app, you will send notification to specific device and in order to send notification to particular device you need token of that device, to get token write this code




FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( login.this,  new OnSuccessListener<InstanceIdResult>() {
    @Override    public void onSuccess(InstanceIdResult instanceIdResult) {

        final String deviceToken = instanceIdResult.getToken();

    }

});


Note: Save token in firebase database and retrieve this token when sending push notification.



Practical Implementation 


There are few steps to implement android firebase push notification.

1. Get Server key from firebase project, to get server key from firebase project, first open firebase project, click on setting gear button, you will see two option that is Project Setting and User permission. Click on project setting then click cloud messaging, you will see server key, copy it and add in project as string. Below are some picture for help.

Firebase Server key part 1
Firebase Server key part 1 
Firebase Server key part 2
Firebase Server key part 2



2Add Firebase messaging library and retrofit library dependence in gradle, code is mentioned is above picture.

3. Add these classes to your project


ApiClient



import retrofit2.Retrofit;

import retrofit2.converter.gson.GsonConverterFactory;



public class ApiClient {



    private static final String BASE_URL = "https://fcm.googleapis.com/";

    private static Retrofit retrofit = null;



    public static Retrofit getClient() {

        if (retrofit == null) {

            retrofit = new Retrofit.Builder()

                    .baseUrl(BASE_URL)

                    .addConverterFactory(GsonConverterFactory.create())

                    .build();

        }

        return retrofit;
    }
}


ApiInterface

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;


public interface ApiInterface {

    @Headers({"Authorization: key=" + Constants.serverkey  , "Content-Type:application/json"})
    @POST("fcm/send")
    Call<ResponseBody> sendNotification(@Body RootModel root);

}


DataModel

You can customize and change this according to your need

public class DataModel {

    private String name;
    private String age;

    public DataModel(String name, String age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

}

NotificationModel

You can customize and change this according to your need

public class NotificationModel {

    private String title;
    private String body;

    public NotificationModel(String title, String body) {
        this.title = title;
        this.body = body;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

}


Rootmodel

It is combination of token (String), Data model and Notification model. 

import com.google.gson.annotations.SerializedName;

public class RootModel {

    @SerializedName("to") //  "to" changed to token    private String token;

    @SerializedName("notification")
    private NotificationModel notification;

    @SerializedName("data")
    private DataModel data;

    public RootModel(String token, NotificationModel notification, DataModel data) {
        this.token = token;
        this.notification = notification;
        this.data = data;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public NotificationModel getNotification() {
        return notification;
    }

    public void setNotification(NotificationModel notification) {
        this.notification = notification;
    }

    public DataModel getMData() {
        return data;
    }

    public void setData(DataModel data) {
        this.data = data;
    }
}



FirebaseNotification

import android.util.Log;

import okhttp3.ResponseBody;
import retrofit2.Callback;

import static android.content.ContentValues.TAG;


public class FirebaseNotification {


    public static void sendNotificationToUser(String token) {

        RootModel rootModel = new RootModel(token, new NotificationModel("Title", "Body"), new DataModel("Name", "30"));

        ApiInterface apiService =  ApiClient.getClient().create(ApiInterface.class);
        retrofit2.Call<ResponseBody> responseBodyCall = apiService.sendNotification(rootModel);


        responseBodyCall.enqueue(new Callback<ResponseBody>() {
            @Override            
 public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                Log.d(TAG,"Successfully notification send by using retrofit.");
            }

            @Override            
public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
       
 Log.d(TAG,"failed notification send by using retrofit." + t.getMessage().toString());

            }
        });
    }
}


4. Create Service class called as MyFirebaseMessagingService

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.Bitmap;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

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



public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "FCM Service";
    private Bitmap bitmap;
    private Context context = this;
    public static final String FIREBASE_TOKEN = "token";


    MainActivity l = new MainActivity();

    @Override
    public void onNewToken(@NonNull String refreshedToken) {
        super.onNewToken(refreshedToken);
        DatabaseReference signin  = FirebaseDatabase.getInstance().getReference().child("user");
        signin.child(l.getName()).child("token").setValue(refreshedToken);


    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getData().size() > 0) {
 sendUserNotification(remoteMessage.getData().get("name"),remoteMessage.getNotification().getBody());
        }

    }


    private void sendUserNotification(String title, String mess) {
        int notifyID = 1;
        Intent intent;
        NotificationChannel mChannel;
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        intent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        String CHANNEL_ID = context.getPackageName();// The id of the channel.
        CharSequence name = "Sample one";// The user-visible name of the channel.
        int importance = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            importance = NotificationManager.IMPORTANCE_HIGH;
        }
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_ID);
        notificationBuilder.setContentTitle(title);
        notificationBuilder.setAutoCancel(true);
        notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
        notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        notificationBuilder.setContentIntent(pendingIntent);
        notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(mess));
        notificationBuilder.setContentText(mess);
        notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
        notificationBuilder.setSmallIcon(getNotificationIcon(notificationBuilder));

        NotificationManager notificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
            notificationManager.createNotificationChannel(mChannel);
        }
        if (notificationManager != null) {
            notificationManager.notify(notifyID /* ID of notification */, notificationBuilder.build());
        }


    }

    private int getNotificationIcon(NotificationCompat.Builder notificationBuilder) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            int color = 0x036085;
            notificationBuilder.setColor(color);
            return R.mipmap.ic_launcher;

        } else {
            return R.mipmap.ic_launcher;
        }
    }

}


5. Add this code where you want to send notification

FirebaseNotification.sendNotificationToUser(token);


These are the 5 steps to implement firebase push notification. You can customize or change code according to your logic. The current will send notification. If you want to send notification to other user, simple use their token. Token is basically receiver address or number in firebase push notification. Every thing is simple or straight forward, if you want the code or project inbox me on facebook. Thank you. 




Previous Post Next Post