Question

i have an android application that can operate with or without a location. handling this case in an activity is straightforward: i set a location listener and wait with a progress dialog, but allow the wait to be aborted by the user (it so happens that if the location provider is disabled, there's no special error is just never returns the location ... nice).

however, i also have a service that requires the location. the service may run before the activity,so i can't depend on the activity to get the location (or not).

the question is how to handle this case in the service. i can wait for the location, but since i can't rely on a user abort, how do i know when to stop waiting, and assume that no location is available? it seems i could do something like,

  1. schedule service with action "get location", which sets the location listener, waits for updates, schedules the same service say 3 minutes later with action "refresh"
  2. in service action "refresh", get the last known location, and be happy with that. it was either obtained or not. if it's null, we know we have no location and we've done the best we can.

it seems like this will work, but it's getting complicated as i can no longer use the simple intent service (i assume), because if the intent service stops itself after onHandleIntent(), then the on location changed event won't be received.

anyway, it's getting sort of complicated, so i'm wondering if there's a simpler way.

Was it helpful?

Solution

answering my own question ... here's how i ended up solving this,

UpdateService - intent service that actually does the update work. this one just calls getLastKnownLocation() to obtain the location.

LocationService - regular service that registers for location updates, and also sets a timer to wake up in 2 minutes. either we get the location update, or the timer goes off. if we get the location update, we cancel the timer. in both cases we unregister for location updates, and start UpdateService to do the actual work, then stop ourself.

we schedule LocationService as the repeating alarm to be our "background" process.

the activity handles things differently. it requests location updates, and puts up a dialog. we either get the location update, or the user cancels the dialog. either way, we unregister for location updates then start UpdateService directly (not LocationService, we already got the location here).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top