我正在使用GPS开发运行的应用程序。我的问题是,当我不走路时,我的GPS返回垃圾值,我的距离计数器会增加,此外我的活动有时会变慢。这是我的“onCreate”代码:
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());
这是我的倾听者:
@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);
}
}
这是我的UI更新处理程序:
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;
}
}
};