Skip to content Skip to sidebar Skip to footer

Call A Method In Activity When Certain Data Recived

I'm trying to build an app that call a method in activity when a certain data is received from server, I use socket for my conection to server and when a certain message recived it

Solution 1:

One way to achieve this is by using BroadcastReceivers. In your class that received the message from the server you can raise an intent like

StringserverResponse= ...;
Stringaction="MESSAGE_RECEIVED_FROM_SERVER";
Intentintent=newIntent();
intent.setAction(action);
intent.putExtra("msg", serverResponse );

context.sendBroadcast(intent);

And now in your activity you need to create an Broadcast Receiver that will register for the MESSAGE_RECEIVED_FROM_SERVERintent. And when receiving the intent you can call the desired method from the activity.

You can use an example from tutorialspoint or vogella.

Hope it helps.

Solution 2:

Depending on your scenario u can adopt given below methods

  • Try using an interface

https://stackoverflow.com/a/16443645/4247543

  • if the above method is not helping then try using EventBus

please follow below link to know more of Event Bus

https://github.com/greenrobot/EventBus

http://gunhansancar.com/ease-communication-between-activities-fragments-services/

  • BroadcastReceiver as mentioned could also help for enabling communication.

https://stackoverflow.com/a/10084754/4247543

  • You can use observers

https://stackoverflow.com/a/30964385/4247543

Hopes it helps.

Post a Comment for "Call A Method In Activity When Certain Data Recived"