Skip to content
Advertisement

How to access a variable of a service from an activity

I understand that in order to access methods of a service from an activity, we should bind the service.

But if we just want to get the value of a variable in the service, can we just access it like so without binding?

JavaScript

It works, but I’m not sure if it has any memory leak implications or any other issues.

Advertisement

Answer

Solution

  • The Activity will send a BroadcastReceiver to the Service to request getting the data.

  • The Service will register the BroadcastReceiver, when receiving a broadcast message from the Activity, it will prepare result data and send it back to the Activity by using ResultReceiver.

Implementation

MyService.java

JavaScript

MainActivity.java

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement