【发布时间】:2015-10-15 08:24:09
【问题描述】:
我一直在关注https://developer.android.com/training/location/index.html 教程。
这是我实现新的 Google 位置 API 的类:
public class GPSTracker implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private final Context context;
private TextView distanceTextView;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Location mLastLocation;
private double totalMeters = 0;
public GPSTracker(Context context, TextView distanceTextView) {
this.context = context;
this.distanceTextView = distanceTextView;
buildGoogleApiClient();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onLocationChanged(Location location) {
double distance = mLastLocation.distanceTo(location);
mLastLocation = location;
totalMeters += distance;
distanceTextView.setText(totalMeters + "");
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000); // Update location every second
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(context, connectionResult.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
一切似乎都完美无缺,但是当我的手机完全没有移动时,每次执行 onLocationChanged 方法时,totalDistance 仍然上升 0.2-0.3 米。
高度赞赏任何防止这种情况的解决方案。
【问题讨论】:
标签: java android android-studio gps google-play-services