i'm developing a running application with GPS. My problem is that when i'm not walking my GPS returns junk values and my distance counter is incremented, furthermore my activity sometimes is slowed. This is my "onCreate" code:
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locListener = new MyLocationListener();
HandlerThread thread = new HandlerThread("MyHandlerThread");
thread.start();
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setSpeedAccuracy(Criteria.ACCURACY_HIGH);
locManager.requestLocationUpdates(locManager.getBestProvider(criteria,false), 0, 0, locListener, thread.getLooper());
And this is my listener:
@Override
public void onLocationChanged(Location loc) {
cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
if (addresses.size() > 0) {
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
}
} catch (IOException e) {
e.printStackTrace();
}
speed = loc.getSpeed() * 3.6; //in km/h
lat = loc.getLatitude();
lon = loc.getLongitude();
if (starting_point) {
last_long = lon;
last_lat = lat;
starting_point = false;
} else {
current_long = lon;
current_lat = lat;
Location locationA = new Location("Previous");
locationA.setLatitude(last_lat);
locationA.setLongitude(last_long);
double distanceMeters = locationA.distanceTo(loc);
double distanceKm = distanceMeters / 1000f;
current_distance = current_distance + distanceKm;
last_long = current_long;
last_lat = current_lat;
}
//send to UI
if (my_handler != null) {
Message msg_ui = my_handler.obtainMessage(GPSActivity.UI_CODE);
Bundle msg_ui_bundle = new Bundle();
msg_ui_bundle.putDouble("LAT", lat);
msg_ui_bundle.putDouble("LON", lon);
msg_ui_bundle.putDouble("SPEED", speed);
msg_ui_bundle.putString("CITY", cityName);
msg_ui_bundle.putDouble("DIST", current_distance);
msg_ui.setData(msg_ui_bundle);
my_handler.sendMessage(msg_ui);
}
}
And this is my UI updating handler:
private static Handler serviceHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UI_CODE:
lat= msg.getData().getDouble("LAT");
lon = msg.getData().getDouble("LON");
speed = msg.getData().getDouble("SPEED");
city_name = msg.getData().getString("CITY");
distance = msg.getData().getDouble("DIST");
tvlat.setText("Lat: "+lat );
tvlon.setText("Lon: "+lon);
tvspeed.setText("Speed: "+speed );
tvcity.setText("City: "+city_name);
tvdistance.setText("Distance: "+distance );
break;
}
}
};