Search code examples
androidgpsandroid-gps

Getting current Location now, not on update


I'm building an app that requires your current location to initialize and show a map. I am requesting location updates with LocationManager.requestLocationUpdates(...), but this only appears to give me data when the location changes (for example I move 10 feet). I am also attempting to use getLastKnownLocation, but in some uncommon cases (like turning the GPS on and without moving opening the app) this will return null for all providers I am making use of.

Whenever getLastKnownLocation returns null, my app can't initialize until I move 10 feet and receive a location update. So far I haven't found a method to poll for my location right now, nor have I found anything suggesting that when I requestLocationUpdates(...) I can get my first data the moment I subscribe and not when I either wait the specified time period or move the specified distance.

One approach would be to requestLocationUpdates(...) on a very small or 0 time interval, get that to send me my current location, delete the LocationListener and again requestLocationUpdates(...) but this time with the much larger value I use to avoid drainig the battery.

I'm looking for a better way to solve this. Probably something like getCurrentLocation(), but really anything that works.


Solution

  • I am requesting location updates with LocationManager.requestLocationUpdates(...), but this only appears to give me data when the location changes (for example I move 10 feet).

    It will give you the first location update as soon as the location is determined -- whether you are moving or not. And it wouldn't be a bad idea to keep listening for more updates for a while as the first one(s) could be less accurate.

    I'm looking for a better way to solve this. Probably something like getCurrentLocation(), but really anything that works.

    If you don't want to receive continuous updates, then what about one of the LocationManager.requestSingleUpdate() variants?

    Those will give you just one location update in the onLocationChanged() callback (or via an Intent) and that's it. No need to cancel any listeners etc. The call could be something like:

    locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, this, Looper.getMainLooper());