I have a service for reading GPS latitude and longitude. I would like to update the activity from the service's locationlistener
's onLocationChanged
.
How can I achieve it? I have been reading on Service Bound but it looks like it is only for activity to invoke the methods in service but not service invoke textView in Activity. Is binding service is not possible to achieve it?
What stops you from declaring a method like this (in your service):
After you gave the reference of the TextView to your Service, it can access it just like any other object.
In the other hand, I do not suggest this solution, because this way it is really easy to cause memory leaks. Also, the TextView should not leave the Activity's context since it is a part of the Activity. The reference would remain in the Service, even after the Activity is destroyed, and I guess you can imagine what would happen if the Service touched the dead TextView.
You should broadcast the updates from your service, and use a
LocalBroadcastRecever
to get those updates in your Activity. That way the TextView will be updated by the one who is responsible for that, the Activity itself.If you don't like the concept of
LocalBroadcatReceiver
you can try any of the event bus solutions. It is more easy to use, and you can pass any kind of objects. You do not have to make them marshallable (Serializable/Parcelable).You should use the LocalBroadcastManager class from within your Service to send an Intent back to the Activity.
For Example, An
Activity
containing a singleTextView
can set up aBroadcastReceiver
like such:And a basic
Service
can broadcast all location changes as follows: