Oleksiy
Oleksiy

Reputation: 39849

Do I need to call requestLocationUpdates() if I just need to find the location once?

All I need is to find user's location when the app starts. Do I still need to create my own listener, implement all methods, and call requestLocationUpdates()? It just seems like a lot of useless code:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 999999999, 999999999, new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
    @Override
    public void onProviderEnabled(String provider) {
    }
    @Override
    public void onProviderDisabled(String provider) {
    }
});

Upvotes: 0

Views: 1186

Answers (3)

janos
janos

Reputation: 124724

I've never used it, but as of API level 9 there is a method called requestSingleUpdate which might what you're looking for.

Another solution is to use requestLocationUpdates and unregister the listener immediately after you received the first update, for example:

@Override
public void onLocationChanged(Location location) {
    locationManager.removeUpdates(this);
    // do something with the received location
}

And in your use case you can leave the other methods of the listener blank, no need to implement them.

Upvotes: 2

tyczj
tyczj

Reputation: 73936

you dont need to but using lastKnownLocation does not guarantee you get an accurate location or even a location at all so you may end up using requestLocationUpdates() anyway to get an accurate location

Upvotes: 1

nahtim
nahtim

Reputation: 96

You can use getLastKnownLocation(provider) to find the last location fix determined by a particular provider.

Location location = locationManager.getLastKnownLocation(provider);

Note that getLastKnownLocation() does not ask the Location provider to update the current position. So if the device has not recently updated the current position this value may not exist or be out of date. The location object returned includes all the position information available from the provider that supplied it like lat, long, bearing, altitude, speed and the time the location fix was taken.

Upvotes: 0

Related Questions