I have an android application. Based on the current geo location of user, I want to fetch some remote data in background and store it. My implementation is:
At speci
but what if I do want the latest location right now, in a service and not activity?
Sorry, but that is not possible, in either a service or an activity. For example, if the GPS radio is off, and you are requesting location data from GPS, it will take tens of seconds just to get a fix, and that's if you are lucky. It might not get a fix at all.
How can I wait for callback to happen and stop my service from returning.
You don't. You do what you said you would do:
use getLastKnownLocation from locationManager as that doesn't respond back by callback
So, have your Service
(which is hopefully an IntentService
) check to see if getLastKnownLocation()
happens to have a value. If it does, use it. Otherwise, registerLocationUpdates()
using a PendingIntent
that will pass control back to your IntentService
. When you get that Intent
, use the location and unregister for updates (assuming the alarm period is nice and long, like, say, once an hour).
Things get tricky if your alarm is a _WAKEUP alarm. You will then need to hold a WakeLock
, so the device does not fall back asleep while you are trying to get a GPS fix. However, you need to release that WakeLock
sometime, and if we cannot get a GPS fix...ummm...well, that's the tricky part. Trying to figure out a nice clean way of handling this, and implementing it as a reusable component (e.g., LocationAlarmService
), is one of 18,000 items on my to-do list.
Also, at what point does lastKnownlocation gets updated? Everytime GPS registers a new location; does it > update it?
AFAIK, yes.