开发者

Android: Communication Activity / Service

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.

Coul开发者_如何学JAVAd 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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜