Android Firebase Messaging: How Update UI from onMessageReceived()

雨燕双飞 提交于 2019-12-01 00:52:27

Yes, you can update UI and pass value to your activity by using Local Broadcast

In your onMessageReceived() Firebase Service.

broadcaster = LocalBroadcastManager.getInstance(getBaseContext());

   Intent intent = new Intent(REQUEST_ACCEPT);
   intent.putExtra("Key", value);
   intent.putExtra("key", value);
   broadcaster.sendBroadcast(intent);

and register local Broadcast in your Activity or fragment method

 @Override
    public void onStart() {
        super.onStart();
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver((receiver),
                new IntentFilter(PushNotificationService.REQUEST_ACCEPT)
        );
    }



    @Override
        public void onStop() {
             super.onStop();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);

        }

and Handle Your update event like this, do your update UI work Here, it will call automatically when notification received and onMessageReceived() send a broadcast.

receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    String   value= intent.getStringExtra("key");
                    String value= intent.getStringExtra("key");

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        };

I believe you should send a Local Broadcast with the data and register a receiver wherever you want that data to be utilised. This is a very good design pattern(Observer) as it decouples your Activity from the Service.

If the activity wants to do something with the data it will, else it won't. They are both separate entities and it would be much easier to maintain this code in the future, as far as I know.

Hope this helped.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!