开发者

Android: Can I use a Broadcast Receiver for periodic GPS location sampling without running a service?

开发者 https://www.devze.com 2022-12-15 10:22 出处:网络
I would like to sample my GPS location periodically, say, every 10 minutes.I\'m assuming that the best way to do this would be to use the LocationManager class with the method:

I would like to sample my GPS location periodically, say, every 10 minutes. I'm assuming that the best way to do this would be to use the LocationManager class with the method:

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

That would broadcast the specified intent that I could then receive in a broadcast rec开发者_Python百科eiver in my application. My question is, if I call this method from an activity, will the broadcasts stop when the process that called the requestLocationUpdate() is killed, or will this registration remain active so that I can continue to get location updates? Do I need to leave a service running to be able to keep the location updates coming when a user moves to different applications? Thanks!


Basically what you said is correct, as far as I'm aware.

I think the registration should remain active even if the Activity dies since you've provided a PendingIntent to the LocationManager. There is no dependency on your task being alive — the PendingIntent contains all the info the framework needs.

From the docs:

even if its owning application's process is killed, the PendingIntent itself will remain usable from other processes that have been given it

It should be pretty simple to test this out anyway. Just start your location updates from your activity or service, then go into the shell and kill off your app and see if the GPS toolbar icon remains and you receive your Intent as expected.

As for leaving a Service running, this should be avoided. Your PendingIntent can start the service for you, leaving it to handle the incoming location Intent, do whatever processing it has to and then stop itself (Service.stopSelf()). It will be started again when the next Intent is fired by the LocationManager.

Just make sure that you unregister from receiving location updates at some point!

0

精彩评论

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

关注公众号