Question Detail

How to implement Firebase Notification android to receive Notification and navigate according to provided action for our android application?

3 years ago Views 1110 Visit Post Reply

Thread Reply

alex levine

- 3 years ago

Add Message Dependency in your gradle file to implement Firebase Push Notification

implementation 'com.google.firebase:firebase-messaging:17.5.0'

 

Add Service to Manifest.xml

<service
    android:name=".notification.MyFirebaseInstanceIDService"
    android:exported="true">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

 

public class MyFirebaseInstanceIDService extends FirebaseMessagingService {

    @Override
    public void onNewToken(String token) {
        super.onNewToken(token);
        Log.d("TAG", "Refreshed token: " + token);
    }
}

 

Create FirebaseMessageingService.java

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.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import com.google.firebase.messaging.RemoteMessage;

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

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Random;

public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {

    Map<String, String> data;
    private static String ADMIN_CHANNEL_ID = "001";
    private NotificationManager notificationManager;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        // TODO(developer): Handle FCM messages here.
        try {
            data = remoteMessage.getData();
            sendNotification(remoteMessage, remoteMessage.getNotification().getBody());//.getNotification().getTitle(), remoteMessage.getNotification().getClickAction(),data.get("product"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.e("dataChat",remoteMessage.getData().toString());
        try{
            Map<String, String> params = remoteMessage.getData();
            JSONObject object = new JSONObject(params);
            Log.e("JSON_OBJECT", object.toString());
        }catch (Exception e) {
    e.printStackTrace();
}


    }


    private void sendNotification(RemoteMessage remoteMessage, String body) throws Exception {
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Intent intent;
        if (remoteMessage.getNotification().getClickAction().equalsIgnoreCase("com.examples.tutorials")) {
            intent = new Intent(getApplicationContext(), TutorialsActivity.class);
        } else if (remoteMessage.getNotification().getClickAction().equalsIgnoreCase("com.examples.ProductScreen")) {
            intent = new Intent(getApplicationContext(), DashboardActivity.class);
        }else if (remoteMessage.getNotification().getClickAction().equalsIgnoreCase("com.examples.MyStore")) {
            intent = new Intent(getApplicationContext(), DetailActivity.class);
            intent.putExtra("Id", Integer.parseInt(remoteMessage.getData().get("id")));
        } else {
            intent = new Intent(getApplicationContext(), DashboardActivity.class); // Here pass your activity where you want to redirect.
            intent.putExtra("product", remoteMessage.getData().get("product"));
        }
       
        String NOTIFICATION_CHANNEL_ID = "101";
        //Setting up Notification channels for android O and above
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            setupChannels();
        }
        long notificationId = new Random().nextInt(60000);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(this, (int) (Math.random() * 100), intent, PendingIntent.FLAG_UPDATE_CURRENT);

        //   Bitmap bitmap = getBitmapFromUrl(remoteMessage.getData().get("image")); //obtain the image
        //Bitmap iconLarge = getBitmapFromUrl(remoteMessage.getNotification().getIcon()); //obtain the image
        // NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();
        //  style.bigPicture(bitmap);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID);
        notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_foreground));
        //notificationBuilder.setColor(ContextCompat.getColor(this, R.color.transparent));
        notificationBuilder.setSmallIcon(getNotificationIcon(notificationBuilder));
        notificationBuilder.setContentTitle(this.getResources().getString(R.string.appname));
        notificationBuilder.setContentText(remoteMessage.getNotification().getBody());
        notificationBuilder.setAutoCancel(true);
        notificationBuilder.setPriority(Notification.PRIORITY_MAX);
        notificationBuilder.setDefaults(Notification.FLAG_AUTO_CANCEL | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND);
        notificationBuilder.setSound(defaultSoundUri);
        notificationBuilder.setWhen(System.currentTimeMillis());
        notificationBuilder.setContentIntent(contentIntent);
        notificationManager.notify((int) notificationId, notificationBuilder.build());
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    private void setupChannels() {
        CharSequence adminChannelName = getString(R.string.appname);
        String adminChannelDescription = getString(R.string.appname);

        NotificationChannel adminChannel;
        adminChannel = new NotificationChannel(ADMIN_CHANNEL_ID, adminChannelName, NotificationManager.IMPORTANCE_LOW);
        adminChannel.setDescription(adminChannelDescription);
        adminChannel.enableLights(true);
        adminChannel.setLightColor(Color.RED);
        adminChannel.enableVibration(true);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(adminChannel);
        }
    }
    private int getNotificationIcon(NotificationCompat.Builder notificationBuilder) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //  int color = #80000000;
            notificationBuilder.setColor(getResources().getColor(R.color.gg));
            return R.mipmap.ic_launcher_foreground;

        }
        return R.mipmap.ic_launcher_foreground;
    }
}