Search code examples
androidlocationandroid-gps

How to use location listener?


Its not clear to me how to use the location listener.

Do I do this:

public Location actualLocation;

private class mLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        actualLocation = location;
    }

    public void onStatusChanged(String s, int i, Bundle b) {
    }

    public void onProviderDisabled(String s) {
    }

    public void onProviderEnabled(String s) {
    }
}

//Middle of code
currentLatitude = actualLocation.getLatitude()
currentLongitude = actualLocation.getLongitude()

or this:

public Location actualLocation;

private class mLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
    }

    public void onStatusChanged(String s, int i, Bundle b) {
    }

    public void onProviderDisabled(String s) {
    }

    public void onProviderEnabled(String s) {
    }
}

//Middle of code
actualLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

currentLatitude = actualLocation.getLatitude()
currentLongitude = actualLocation.getLongitude()

There are variables used that were not declared in this snippets of code. It's on purpose. I shortened the code for the sake of simplicity.

UPDATE: My question was: ¿Do I use getLastKnow location or do I manually save the location every run be it updates? ¿Would that work the same?


Solution

  • You need to call LocationManager.registerLocationUpdates. You pass the LocationListener into that call, and the framework will call those functions whenever it has a new location.