Reputation: 352
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?
Upvotes: 0
Views: 1651
Reputation: 385
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 :)
Upvotes: 1
Reputation: 116
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");
}
Upvotes: 0