Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Android UI from firebase callback

I am novice in android programming and I am trying to implement a simple app making use of push notification using firebase. I setup the android project (using Android Studio 2.2) folowing google documentation and I am able to get notification both with app in foreground than in background. I have two class that extends FirebaseMessagingService (named MyFirebaseMessagingService) and FirebaseInstanceIdService (named MyFirebaseInstanceIDService).

In the first one I have the method onMessageReceived implemented that is triggered when the app is in foreground or when I receive a "data" tag as part of the notification. So I have this piece of code inside:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        String cappello;
        cappello = remoteMessage.getNotification().getBody();
    }

Now my problem is to update a textView in the main layout using the variable "cappello" mentioned above. How can I do that? I have found some example using different classes but all of them seems to be something different from that case.

Ho can I trigger an action to update some parts of the main layout ? A texView for example ?

like image 593
mrcbis Avatar asked Sep 23 '16 15:09

mrcbis


1 Answers

Use a broadcast receiver and register it in your activity, Which gets triggered when new message comes

Short example, In your FirebaseMessagingService::onMessageReceived, you may have this:

cappello = remoteMessage.getNotification().getBody();
Intent intent = new Intent();
intent.putExtra("extra", cappello); 
intent.setAction("com.my.app.onMessageReceived");
sendBroadcast(intent); 

Then in your MainActivity, you implement a BroadcastReceiver :

private class MyBroadcastReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {
    Bundle extras = intent.getExtras();
    String state = extras.getString("extra");
    updateView(state);// update your textView in the main layout 
  }
} 

and register for it in onResume() of MainActivity:

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.my.app.onMessageReceived");
MyBroadcastReceiver receiver = new MyBroadcastReceiver();
registerReceiver(receiver, intentFilter); 
like image 174
Rissmon Suresh Avatar answered Oct 18 '22 02:10

Rissmon Suresh