1

I am trying to get notification generated by FCM console and I am receiving them but I am unable to override onMessageReceived of FirebaseMessagingService. Don't know what I am doing wrong.

MyFirebaseMessagingService class responsible for handling notifications:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d(TAG, "FROM:" + remoteMessage.getFrom());

        //Check if the message contains data
        if(remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data: " + remoteMessage.getData());
        }

        //Check if the message contains notification

        if(remoteMessage.getNotification() != null) {
            Log.d(TAG, "Mesage body:" + remoteMessage.getNotification().getBody());
            sendNotification(remoteMessage.getNotification().getBody(),remoteMessage.getData());
        }
    }

    /**
     * Dispay the notification
     * @param body
     */
    private void sendNotification(String body , Map<String,String> data) {

//        int finalSecId = Integer.parseInt((String) data.get("sec_id"));
//        int sec = Integer.parseInt((String) data.get("sec"));
        Intent intent = new Intent(this, InsuranceActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0/*Request code*/, intent, PendingIntent.FLAG_ONE_SHOT);
        //Set sound of notification
        Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notifiBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.login_meter)
                .setContentTitle(getString(R.string.app_name))
                .setContentText((String) data.get("sec_id")+ " "+(String) data.get("sec"))
                .setAutoCancel(true)
                .setSound(notificationSound)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0 /*ID of notification*/, notifiBuilder.build());
    }
}

And Inside Application tag

<service android:name=".Fcm.MyFirebaseMessagingService"
            android:enabled="true"
            android:exported="true"
            >
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
        <service android:name=".Fcm.MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>
Mehvish Ali
  • 732
  • 2
  • 10
  • 34
  • you need to send DATA instead of Notification from server and at Message data you have to show NOTIFICATION – Divyesh Patel May 29 '17 at 04:40
  • Actually the data is sent from the FCM console but I am unable to handle it in a service onMessageReceived is not triggered and I am unable to see the results for specific tag in logs as well – Mehvish Ali May 29 '17 at 04:43
  • then in fcm console, use ADVANCED option and send data in key-value pair. After that you can receive data in OnMessageReceived() – Divyesh Patel May 29 '17 at 04:45
  • doing that as well – Mehvish Ali May 29 '17 at 04:46
  • actually in foreground its triggered but in background it isnt – Mehvish Ali May 29 '17 at 04:46
  • you have to use DATA paylod for background/foreground state, and use remoteMessage.getData() to show value in notification – Divyesh Patel May 29 '17 at 04:49
  • 1
    So, you are receiving notification both in foreground and background, but the background notification isn't opening **InsuranceActivity**, rather it always opens the MainActivity... is it the case? – Sudip Podder May 29 '17 at 05:07
  • @Sudip yes this is the case – Mehvish Ali May 29 '17 at 05:17
  • Okay, I will try to write an answer in a while. Are you only using firebase console to send notification or also using firebase API? – Sudip Podder May 29 '17 at 05:26
  • I am having an API its working fine with both cases just require client side solution – Mehvish Ali May 29 '17 at 05:29
  • If you are using API, you can try the **method 2** of this answer: https://stackoverflow.com/a/39330797/5829624 – Sudip Podder May 29 '17 at 05:53
  • The idea is: send a custom_value with 'click_action' key inside the notification payload. use that custom_value inside an intent-filter of your Activity (which you want to open). and you should be good to go. – Sudip Podder May 29 '17 at 05:56
  • My activities are dynamic depending upon the key value pair showing which section to move towards e.g `$fields = array( 'to' => $token, 'notification' => array('title' => 'Motors City', 'body' => $message), 'data' => array( 'sec_id' => $secID, 'sec' => $sec, 'extra1'=>$extra1, 'extra2'=>$extra2 ) );` – Mehvish Ali May 29 '17 at 05:59

5 Answers5

2

There are two types of FCM

notification Messages: Sending a payload with this message type triggers onMessageReceived() only when your app is in foreground.

data Messages: Sending a payload with only this specific message type triggers onMessageReceived() regardless if your app is in foreground/background.

Reference:here

Ratilal Chopda
  • 4,162
  • 4
  • 18
  • 31
1

I had this problem of handling the notifications from FCM.

First we have to understand that there are 2 types of notifications.

  1. Notification - It will trigger when your app is not in foreground and generate a notification. If you click on it then it will open the launcher activity.

  2. Data notification - This one is used to parse the data and it is received in background as well as foreground. So you can build a custom notification based on the data provided in the data object by the FCM Push.

     Map<String ,String> dataMap = remoteMessage.getData();
    

    Here i created a simple Map with key value pairs. Now i can receive the title of the notification in the data object and make a simple notification with a custom intent.

I personally use a context object to determine if the app is in foreground or background. Based on that i decide if i have to show the notification or just update the data.

Hope this helps.

Sarthak Gandhi
  • 2,130
  • 1
  • 16
  • 23
1

Extending #Sudip Podder comments and #Ratilal Chopda answer Follow these steps:

Step1:

<activity android:name=".SplashActivity">
        <intent-filter>
            <action android:name=".SplashActivity" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

Step2:

I am using php at server so you need to adjust things the way you like but in notification payload add "click_action" : ".SplashActivity"

 $fields = array(
            'to' => $token,
            'notification' => array(
                'title' => 'Motors City',
                'body' => $message,
                "click_action" => ".AppSplash",

            ),
            'data' => array(
                'sec_id' => $secID,
                'sec' => $sec,
                'extra1'=>$extra1,
                'extra2'=>$extra2
            )
        );

        $headers = array(
            'Authorization:key=' . $server_key,
            'Content-Type:application/json'
        );

Step3: In Oncreate of your SplashActivity

Bundle bundle = getIntent().getExtras();
if (bundle != null) {
  Log.d(TAG,bundle.toString);
}}

and you are done

Faisal Naseer
  • 4,110
  • 1
  • 37
  • 55
0

Right now you are having Notification in notification type, which triggers Notification Default,and Just open the app on the click of the notification.

So you need to change server side code from notification type to data type. And try to get Message from

`remoteMessage.getData()`  not from `remoteMessage.getNotification()`

if you want to manage click of the notification use data type notification.to understand more about this types go through this link https://firebase.google.com/docs/cloud-messaging/concept-options

9spl
  • 357
  • 1
  • 11
-1

Try this

 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);
Mohammad nabil
  • 1,010
  • 2
  • 12
  • 23