0

I have a service bound to an activity. I defined an interface that is implemented by the activity. In the service I have an object of the interface that implements the activity, i give memory to this object when I call the method that returns the binder.

The service implements socket.io when I receive a message from the server, I call the interface method to update data in the activity.

My question is, am I using bad practices? Should I implement a LocalBroadcastReceiver to communicate with the activity instead of using the interface?

what do you suggest me?

  • You have to post in English here or use the spanish site: https://es.stackoverflow.com/ – Ibo Nov 14 '17 at 01:13
  • There is good discussion https://stackoverflow.com/questions/2463175/how-to-have-android-service-communicate-with-activity and https://stackoverflow.com/questions/20594936/communication-between-activity-and-service – Shobhit Puri Nov 14 '17 at 01:38

1 Answers1

0

Short answer is yes it is really a bad practice.

Long answer, even though you reference your activity over an interface it's still the same object in the memory. So let's say you have long running operation on your service then when the activity is recreated after a rotation or any kind of configuration change your old reference will be kept in the Service and it will be leaked.

So since your question is too generic I can just list the alternative methods, you can look through all of them and apply whichever fits on your style.

  1. EventBus (Publish/Subscribe pattern, the easiest solution)
  2. Dependency Injection (Use Dagger or similar to inject your model on both Activity and Service
  3. BroadcastReceiver
  4. Messenger
Gunhan
  • 6,807
  • 3
  • 43
  • 37