Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How can I update data or UI in my Activity when Push Notification FCM is received?

I have the following FirebaseMessagingService which works fine when I get a push notification and the app is in foreground:

public class _FCMService extends FirebaseMessagingService {
   @Override
   public void onMessageReceived(RemoteMessage remoteMessage) {
      if (remoteMessage.getData().size() > 0) {
         // Log.i(TAG, "PUSH PAYLOAD: " + remoteMessage.getData());

         JSONObject pushData = new JSONObject(remoteMessage.getData());
         pushType = pushData.optString("pushType");
         pushMessage = pushData.optString("body");
         Log.i(TAG, "ON PUSH RECEIVED - pushType: " + pushType);
         Log.i(TAG, "ON PUSH RECEIVED - pushMessage: " + pushMessage);


         Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
         NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                 .setContentText(pushMessage)
                 .setStyle(new NotificationCompat.BigTextStyle())
                 .setAutoCancel(true)
                 .setSmallIcon(R.mipmap.ic_launcher)
                 .setSound(defaultSoundUri);
         NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
         assert notificationManager != null;
         notificationManager.notify(0 , notificationBuilder.build());
      }
   }



   @Override
   public void onNewToken(@NotNull String token) {
      Log.i(TAG, "Refreshed token: " + token);
      ANDROID_DEVICE_TOKEN = token;
   }
}

So, If I receive a push, the Logcat prints out the notification's body and (if present) the pushType string.

What I would need to do is to make my other Activity update data when push is received, as well as get the pushMessage and pushType strings.

I know how to do that in iOS Swift - by using NotificationCenter - but have no idea about Android, I've tried LocalBroadcaster, but no success.

like image 460
Frank Eno Avatar asked Sep 05 '25 03:09

Frank Eno


2 Answers

LocalBroadcastManager is now deprecated!

You can use LiveData implementation in a static reference and observe it in the Activity or Fragment

public class NotificationService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        
        Notification.
                    getInstance().
                    addOrder(remoteMessage.getData().get("id"));
        
    }

    public static class Notification {
        private static Notification instance;
        private MutableLiveData<String> newOrder;

        private Notification() {
            newOrder = new MutableLiveData<>();
        }

        public static Notification getInstance() {
            if(instance == null){
                instance = new Notification();
            }
            return instance;
        }

        public LiveData<String> getNewOrder() {
            return newOrder;
        }

        public void addOrder(String orderID){
            newOrder.postValue(orderID);
        }
    }
}

And In the Activity or Fragment:

NotificationService.
   Notification.
       getInstance().
       getNewOrder().
       observe(getViewLifecycleOwner(), new Observer<String>() {
           @Override
           public void onChanged(String s) {
               //TODO: update your ui here...
           }
       });
like image 116
Jossué O. Rodríguez Avatar answered Sep 08 '25 00:09

Jossué O. Rodríguez


You can add a .setContentIntent(NotificationChannelUtil.createPendingIntent(this, pushMessage, pushType)) to your notificaitionBuilder.

Where that function is inside an util class like:

public class NotificationChannelUtil {

    private NotificationChannelUtil() {}

 public static PendingIntent createPendingIntent(Context context, String pushMessage, String pushType) {
        Intent intent = new Intent(context, YourWantedActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("pushMessage", pushMessage);
        intent.putExtra("pushType", pushType);
        return PendingIntent.getActivity(context, 0 /* request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);
    }
}
like image 31
Septimiu Avatar answered Sep 07 '25 22:09

Septimiu