Search code examples
javaandroidandroid-location

How to stop automatic updates of Location


I'm creating an app which updates the location(lat,long) everytime a button is clicked. I have set an OnClickListener on the button which calls this method -

 void getLocation() {
    try{
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //Default minTime = 5000, minDistance = 5
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, this);
    }
    catch (SecurityException e) {
        e.printStackTrace();
    }
}

But the problem is that the location keeps updating itself, in small time periods. I want the location to stay the same and only update itself when the button is pressed. What modifications must I make to do that?

Here is the onLocationChanged() method for reference -

@Override
public void onLocationChanged(Location location) {

    locationText.setText("Current Location: "+ location.getLatitude() + " , " + location.getLongitude());
}

And also, sometimes it shows the location within a second, while other times it takes 10seconds. Any reason/solution for that?


Solution

  • Actually there's no need for requestLocationUpdates() in the first place, when you don't want automatic location updates.

    So instead of

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, this);
    

    just use

    locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, this, null);
    

    Then you'll get only one callback per click on the button.

    Regarding the time period when you get the callback: Android strives to reduce battery consumption as far as possible. That includes that the location is not detected each time a single app requests it, but requests are bundled, so that one received location is delivered to multiple apps or services that requested the location.