13

I'm using

myLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

to retrieve the current location at the start-up of my application.

As the Android documentation states, this location can be "out-of-date", since the method returns the location when the GPS was used the last time.

How can I actively request the current location from the GPS? I thought about using LocationListener, however that might be a bit of an overkill, since I only need the location once (at the start of my app).

Any ideas?

znq
  • 44,613
  • 41
  • 116
  • 144

1 Answers1

12

Your initial intuition is correct - you need to use a LocationListener to request updates. Given that you require only a single position, you can unregister the LocationListener after the first value returns.

In practice though, it's probably wise to listen for a little bit longer. Location Based Services (particularly GPS) have a tendency to 'jump around' a bit when they first get their fix. Your best bet is to listen for a set amount of time, or a set number of updates, or until a certain level of accuracy has been achieved (the Location Listener will return the accuracy of the position returned).

Reto Meier
  • 96,655
  • 18
  • 100
  • 72
  • Suppose I already enable GPS, and then start my app. If I stay at one place, then onLocationChanged() won't be called. Under this case, how can I make sure that the return value of getLastKnownLocation() is not out-of-date? – flypen Oct 26 '11 at 05:08
  • You can specify updates based on time as well, have a look at requestLocationUpdates – Hein du Plessis Aug 31 '12 at 08:08