我可以使用传感器api实时获取步骤数据。 我也可以实时获取距离数据。 但是,我不能一步到位。
private void registerFitnessDataListener(final DataSource dataSource, final DataType dataType) {
if (mListener == null)
mListener = new OnDataPointListener() {
@Override
public void onDataPoint(DataPoint dataPoint) {
isUpdatingStep = false;
if (!isUpdatingStep) {
for (Field field : dataPoint.getDataType().getFields()) {
if (String.valueOf(field).equals("steps(i)")) {
thisActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (!isUpdatingStep) {
}
}
});
} else if (String.valueOf(field).equals("distance(f)")) {
thisActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (!isUpdatingStep) {
}
}
});
}
}
}
}
};
SensorRequest req = new SensorRequest.Builder()
.setDataSource(dataSource)
.setDataType(dataType)
.setSamplingRate(2000, TimeUnit.MILLISECONDS)
.build();
Fitness.SensorsApi.add(
mClient,
req,
mListener)
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
if (status.isSuccess()) {
} else {
}
}
});
}
private void findFitnessDataSources(final DataType dataType) {
Fitness.SensorsApi.findDataSources(mClient, new DataSourcesRequest.Builder()
.setDataTypes(dataType)
.setDataSourceTypes(DataSource.TYPE_DERIVED)
.build())
.setResultCallback(new ResultCallback<DataSourcesResult>() {
@Override
public void onResult(DataSourcesResult dataSourcesResult) {
for (DataSource dataSource : dataSourcesResult.getDataSources()) {
if (dataSource.getDataType().equals(DataType.TYPE_STEP_COUNT_DELTA)) {
registerFitnessDataListener(dataSource, DataType.TYPE_STEP_COUNT_DELTA);
setDailySteps();
} else if (dataSource.getDataType().equals(DataType.TYPE_DISTANCE_DELTA)) {
registerFitnessDataListener(dataSource, DataType.TYPE_DISTANCE_DELTA);
setDailyDistance();
}
}
}
});
}
private void buildFitnessClient() {
if (mClient == null && checkPermissions()) {
mClient = new GoogleApiClient.Builder(getActivity())
.addApi(Fitness.SENSORS_API)
.addApi(Fitness.HISTORY_API)
.addScope(Fitness.SCOPE_ACTIVITY_READ)
.addConnectionCallbacks(
new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle bundle) {
findFitnessDataSources(DataType.TYPE_STEP_COUNT_DELTA);
findFitnessDataSources(DataType.TYPE_DISTANCE_DELTA);
}
@Override
public void onConnectionSuspended(int i) {
if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
} else if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
}
}
}
)
.enableAutoManage(getActivity(), 0, new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult result) {
}
})
.build();
}
}
聚苯乙烯。当我评论其中一个功能。 findFitnessDataSources(DataType.TYPE_STEP_COUNT_DELTA);
或findFitnessDataSources(DataType.TYPE_DISTANCE_DELTA);
buildFitnessClient()
中的。
该应用可以正常工作。(仅更新一个值)
答案 0 :(得分:1)
将调用函数中的 findFitnessDataSources 方法的采样率更改为不同可能会解决此问题。