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?