我一直在使用传感器来检测步骤,并希望将源更改为历史记录(我想今天获得总步骤)。我遵循了多个堆栈溢出和教程(大部分是谷歌自己的)。这是我的代码,它在一个粘性服务中创建的类中。
private void buildFitnessClient() {
mClient = new GoogleApiClient.Builder(context)
.addApi(Fitness.HISTORY_API)
.build();
mClient.connect();
DataReadRequest readRequest = new DataReadRequest.Builder()
.aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
.bucketByTime(1, TimeUnit.DAYS)
.setTimeRange(
DateTime.now().minusDays(5).getMillis(),
DateTime.now().getMillis(),
TimeUnit.MILLISECONDS)
.build();
Fitness.HistoryApi.readData(mClient, readRequest).setResultCallback(new ResultCallback<DataReadResult>() {
@Override
public void onResult(DataReadResult dataReadResult) {
Log.d(TAG, "onResult");
Log.d(TAG, "" + dataReadResult.getBuckets().size());
for (Bucket bucket : dataReadResult.getBuckets()) {
List<DataSet> dataSets = bucket.getDataSets();
for (DataSet dataSet : dataSets) {
Log.d(TAG, "dataSet.dataType: " + dataSet.getDataType().getName());
for (DataPoint dp : dataSet.getDataPoints()) {
Log.d(TAG, "dp:" + dp.toString());
}
}
}
}
});
Log.d(TAG, "Dataset in History end ");
}
从本质上讲,什么都没发生。我看不到日志"onResult"。怎么了?是客户端构建的吗?背景?参数?
谢谢!
答案是我没有适当的权限。我更改了一些类并删除了应用程序数据,因此我失去了权限,也没有任何恢复它们的措施。
所以,需要什么:
检查api客户端是否已连接(使用addOnConnectionFailedListener
),如果连接失败,请运行类似以下的代码:
//ConnectionResult result = intent.getExtras().getParcelable(OrderKeys.FITNESS_CONNECTION_FAILED_RESULT);
// This is my solution for service-activty communication, this is run in activty
Log.i(TAG, "Connection failed. Cause: " + result.toString());
if (!result.hasResolution()) {
// Show the localized error dialog
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(),
LifeAidActivity.this, 0).show();
return;
}
// The failure has a resolution. Resolve it.
// Called typically when the app is not yet authorized, and an
// authorization dialog is displayed to the user.
if (!authInProgress) {
try {
Log.i(TAG, "Attempting to resolve failed connection");
authInProgress = true;
result.startResolutionForResult(LifeAidActivity.this,
REQUEST_OAUTH);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG,
"Exception while starting resolution activity", e);
}
}