0

I had implemented Android push notifications and I can handle it when app is running extending FirebaseMessagingService with this method:

@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
   ...
}

But what I really need is to get the notification data in my current activity to update some fields to the user see it in real time. But I can't find a way to do this. Could someone help me?

dm707
  • 352
  • 2
  • 15
  • 1
    You just need to route the data from the service to your activity, see here: https://stackoverflow.com/questions/18125241/how-to-get-data-from-service-to-activity – Daniel Nugent Oct 08 '19 at 22:18

2 Answers2

1

Create a local broadcast receiver
When you receive a notification at FirebaseMessagingService, you will send the data to the activity that you need with a LocalBroadcastReceiver. It's easy and safe.

On your FirebaseMessagingService

@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);

//Take the data from message received
String myData = remoteMessage.get("MyDataKey");

//Send data through a local broadcast receiver
Intent intent = new Intent("IntentFilterAction");
intent.putExtra("MyDataKey", myData);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

On activity onCreate

//Create BroadcastReceiver
BroadcastReceiver broadcastReceiver = new BroadcastReceiver(){
      @Override
      public void onReceive(Context context, Intent intent) {
          super.onReceive(context, intent);

          //Get data from intent
          String mydata = intent.getExtras
      }
};

IntentFilter intentFilter = new IntentFilter("IntentFilterAction");
LocalBroadcastManager.getInstance(getContext()).registerReceiver(broadcastReceiver, intentFilter);

On activity onDestroy

//Unregister BroadcastReceiver
LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(broadcastReceiver);

Hope it helps :)

0

check this out from the docs:

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

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

    }

}



public void updateData(Map<String, String> data){
        // update your data here
        //ex: editText1.setText("text");
    }
Bilal Awwad
  • 114
  • 6
  • That code in the docs is for a Service, not an activity. The challenge is getting the data payload to the activity from the service. – Daniel Nugent Oct 08 '19 at 22:17
  • @DanielNugent then maybe try 1) save the data in a shared preferences and retrieve them from the activity. or 2) prepare a [pending intent](https://developer.android.com/reference/android/app/PendingIntent) and get the data from it when starting your activity. i think this will solve it if i understand the issue correctly – Bilal Awwad Oct 09 '19 at 23:24