我正在构建一个需要使用 Google Fit 的 Android API 获取用户当前速度的应用程序。API 使用 findDataSources 方法毫无问题地找到了 DataType.TYPE_SPEED,但是速度值永远不会返回。我的代码如下:
private void buildFitnessClient() {
mClient = new GoogleApiClient.Builder(this)
.addApi(Fitness.SENSORS_API)
.addScope(new Scope(Scopes.FITNESS_LOCATION_READ))
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle bundle) {
showToast("Connected");
//Calls to the Fitness API
Fitness.SensorsApi.findDataSources(mClient, new DataSourcesRequest.Builder()
// At least one datatype must be specified.
.setDataTypes(DataType.TYPE_SPEED)
.build())
.setResultCallback(new ResultCallback<DataSourcesResult>() {
@Override
public void onResult(DataSourcesResult dataSourcesResult) {
String text = "";
for (DataSource dataSource : dataSourcesResult.getDataSources()) {
text += "Data Source type: " + dataSource.getDataType().getName() + "\n";
if(dataSource.getDataType().equals(DataType.TYPE_SPEED) && mListener == null) {
showToast("mListener");
registerFitnessDataListener(dataSource, DataType.TYPE_SPEED);
}
}
tvaveragespeed.setText(text);
}
});
}
@Override
public void onConnectionSuspended(int i) {
if(i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST)
showToast("Connection lost. Cause: Network lost");
else if(i == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED)
showToast("Connection lost. Cause: Service disconnected");
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Connection failed. Reason: " + connectionResult);
if(!connectionResult.hasResolution()) {
//Show localized error dialog
GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(),
MainActivity.this, 0).show();
return;
}
if(!authInProgress) {
try {
Log.d(TAG, "Attempting to resolve failed connection");
authInProgress = true;
connectionResult.startResolutionForResult(MainActivity.this,
REQUEST_OAUTH);
}catch(IntentSender.SendIntentException e) {
showToast("Exception while starting resolution Activity");
}
}
}
}).build();
}
private void registerFitnessDataListener(DataSource dataSource, DataType dataType) {
mListener = new OnDataPointListener() {
@Override
public void onDataPoint(DataPoint dataPoint) {
for(Field field : dataPoint.getDataType().getFields()) {
Value val = dataPoint.getValue(field);
showToast("val");
tvaveragespeed.setText(val.toString());
}
}
};
Fitness.SensorsApi.add(
mClient,
new SensorRequest.Builder()
.setDataSource(dataSource)
.setDataType(dataType)
.setSamplingRate(10, TimeUnit.SECONDS)
.build(),
mListener)
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
if(status.isSuccess()) {
showToast("Speed listener registered");
}else{
showToast("Problem while registering listener");
}
}
}
);
}
我究竟做错了什么?谢谢