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 specific interval a alarm fires up my service. Service uses an anonymous class to query current location and registers a locationListener callback. On call of onLocationChanged() I initiate the remote data fetch from server.
However once my service is done registering the location listener using anonymos class, it returns as expected; as it doesn’t wait for callback to happen before finishing. Since callback takes some time and makes a call when service has already returned, it throws an error saying:
java.lang.RuntimeException: Handler{43e82510} sending message to a Handler on a dead thread
Which is quite understandable. One quick workaround for me now is that I can use getLastKnownLocation from locationManager as that doesn’t respond back by callback; but what if I do want the latest location right now, in a service and not activity? How can I wait for callback to happen and stop my service from returning.
Also, at what point does lastKnownlocation gets updated? Everytime GPS registers a new location; does it update it? What I want to know is that if it’s not latest can it still be closed to latest? As I didn’t see an option in android emulator to configure the time period between subsequent updates.
Any help is much appreciated.
Cheers
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.
You don’t. You do what you said you would do:
So, have your
Service(which is hopefully anIntentService) check to see ifgetLastKnownLocation()happens to have a value. If it does, use it. Otherwise,registerLocationUpdates()using aPendingIntentthat will pass control back to yourIntentService. When you get thatIntent, 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 thatWakeLocksometime, 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.AFAIK, yes.