Loïc Noest
Loïc Noest

Reputation: 125

Android FCM Notification use the data in a RemoteMessage

I have an app that uses FCM to send messages between users. I have implemented my FirebaseMessagingService that does something with the data of the RemoteMessage. This is an example of a RemoteMes:

{
"to" : "cZVz2c3uJBg:APA91bHW...",
"data" :{"friend": "mike"},
"notification" : {
  "title" : "Paltrack",
  "sound" : "true",
  "click_action" : "com.woutkl.groep_2.RegActivityStart"
  }
}

The first problem i had is that (if this is correct) onMessageReceived is not called when the app is not in foreground. So to do somthing after you click the notification I start that activity, but now i need to access the data from the RemoteMes and i have no idea how to do this.

Upvotes: 0

Views: 1676

Answers (2)

Sathish Kumar VG
Sathish Kumar VG

Reputation: 2172

When app in background at that time cannot get notification value from "notification" param . At that time we can get value from "data" param. So whatever we want to display in notification we need to get response of same data with both "data" and "notification" param values from server back end.

Whenever clicking the notification at that time we can get that notification message through "data" param in notification message with laucher activity.

AndroidManifest.xml :

<activity
    android:name=".view.SplashActivity"
    android:screenOrientation="portrait">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

In launcher activity we can get notification msg information after clicked notification.

SplashActivity:

public class SplashActivity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
Bundle bundle = getIntent().getExtras();
if (bundle != null && bundle.get("data")!=null) {
    String datas = bundle.get("data").toString();
    Log.e("splash of pushfcm", datas);
    try {
        JSONObject obj = new JSONObject(datas);
        String text = obj.getString("friend");
    } catch (JSONException e) {
        e.printStackTrace();
    }
} else {
    //Log.d("fcm no data", "no data in fcm");
}
}
}

Upvotes: 1

Kushan
Kushan

Reputation: 5984

Firebase messages with both data and notification will not call onMessageReceived when the app is in background. This is by design.

When the notification gets clicked, the data is added to the intent which launches your activity as extras.

in your activity, get the intent extras:

Bundle extras = getIntent().getExtras();

Now get all the tags in your extras... and use what you need:

if(extras!=null){
   Set<String> keysInExtras = extras.keySet();

   for(String key : keysInExtras){
     //find the keys you need and get the data from the bundle using those keys
   }

}

Upvotes: 1

Related Questions