Aayush Kucheria
Aayush Kucheria

Reputation: 19

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?

Upvotes: 0

Views: 227

Answers (3)

Headcracker
Headcracker

Reputation: 531

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.

Upvotes: 1

jorjSB
jorjSB

Reputation: 610

You can use

locationManager.removeUpdates(this);

More info here

Upvotes: 1

OneCricketeer
OneCricketeer

Reputation: 191983

If you only want to update when the button is clicked, you can simply store the value in the callback and not update the UI until you click the button

private Location mLocation;
@Override
public void onLocationChanged(Location location) {
     mLocation = location;
}

Move this into the button click method

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

The accuracy of the GPS probably has something to do with how frequently its updated

Upvotes: 1

Related Questions