Search code examples
javaandroidlocationlocationmanagerlocationlistener

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) {
    }
});

Solution

  • 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.