How can I measure the distance traveled after pressing a button on android?

0

I have implemented several methods to be able to add the distance traveled, whether walking or running, etc ... all with LocationListener. I'm implementing it on api +23 handling the permissions.

@Override
public void onLocationChanged(Location location) {
    Log.i("Location", "lat: " + location.getLatitude());
    Log.i("Location", "lng: " + location.getLongitude());
    String str="Location"+ location.getLongitude();
    Toast.makeText(this,str,Toast.LENGTH_LONG).show();

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {


}

@Override
public void onProviderDisabled(String s) {

}

But I need to do it after pressing a start button. I have followed several SO questions, like this link for example . And some more but I have not found the solution.

Edition:

After some suggestions like the ones below I did this:

@Override
public void onClick(View view) {
    if (view.getId() == R.id.bIniciar) {

        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
        provider = locationManager.getBestProvider(new Criteria(), false);
        location = locationManager.getLastKnownLocation(provider);
        setOldLoc(location);

    }
}



@Override
public void onLocationChanged(Location location) {
        setNewLoc(location);
        distance=getDistance()+(getOldLoc().distanceTo(getNewLoc()));
        setDistance(distance);
        setOldLoc(location);

    distancia.setText("Recorrido:"+String.valueOf(getDistance()));


}

But even if the device is stopped, it keeps changing the coordinates in "OnLocationChanged".

Any suggestions?

    
asked by Matias Blanco 19.03.2018 в 02:26
source

1 answer

0

From onClick you should call:

 locationManager.requestLocationUpdates( ...

To start obtaining the location as you change position, then within onLocationChanged you keep the latitude and longitude and calculating the distance according to the points.

Review the method parameters requestLocationUdpates , there is a parameter that is minDistance , there you can put a minimum distance in meters so you can enter onLocationChanged

    
answered by 19.03.2018 в 13:17