tags:

views:

470

answers:

1

Hi,

I have some questions concerning the communication between an Activity and a Service. I'd like to write a speedmeter application, where the UI is constantly updated with new data derived from the GPS sensor.

So far, I have an LocationListener running in a service. What is the best practice in Android:

1) Access the service from an Activity, let's say every second and update the UI. Or,
2) Let the service update the UI.

Could you provide some helpful links for case 2), please?.

Case 1) shouldn't be a problem with a LocalService and an IBinder interface, right?

Thanks!

A: 

You have a service which is receiving location updates and you want to know the best way to keep the Activity display updated in real time.

Actually a Service is not required to "record tracks in the background". Instead use a BroadcastReceiver and use the version of requestLocationUpdates(..) that takes a PendingIntent. The PendingIntent you pass into requestLocationUpdates(..) should point at the BroadcastReceiver where you can do the business of recording the latest tracks location.

requestLocationUpdates(String provider, long minTime, float minDistance, PendingIntent intent)

Ok, so now you have a BroadcastReceiver updating your database with track data. If you are using a ContentProvider (rather than a database directly) then you can make your Activity watch the database for changes. You can do this by calling ContentResolver's registerContentObserver(..) method in onResume().

getContentResolver().registerContentObserver(uri, false, yourContentObserver);

Just make sure you call unregisterContentObserver(yourContentObserver) in your onPause() method.

Spencer Riddering
Thanks a lot. I messed around with static classes and the Observer interface, but your solution looks pretty nice.