我可以使用Google Fit Sensor Api获取卡路里和距离吗? 我写了实时健身应用程序,它应该显示当前数据,必须每秒更新一次。
我认为以我的方式使用会话Api或历史Api不是一个好主意。 如果我错了,请纠正我。我只能找到实时手动获取步骤
加了: 在下面的代码中,仅工作TYPE_STEP_COUNT_CUMULATIVE,例如TYPE_DISTANCE_CUMULATIVE不起作用
private void buildFitnessClient() {
if (mClient == null) {
mClient = new GoogleApiClient.Builder(getActivity())
.addApi(Fitness.SENSORS_API)
.addScope(new Scope(Scopes.FITNESS_LOCATION_READ))
.addConnectionCallbacks(
new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected!!!");
findFitnessDataSources();
}
@Override
public void onConnectionSuspended(int i) {
if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
Log.i(TAG, "Connection lost. Cause: Network Lost.");
} else if (i
== GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
Log.i(TAG,
"Connection lost. Reason: Service Disconnected");
}
}
}
)
.enableAutoManage((MainActivity)getActivity(), 0, new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Google Play services connection failed. Cause: " +
result.toString());
}
})
.build();
}
}
private void findFitnessDataSources() {
Fitness.SensorsApi.findDataSources(mClient, new DataSourcesRequest.Builder()
.setDataTypes(DataType.TYPE_DISTANCE_CUMULATIVE)
.setDataSourceTypes(DataSource.TYPE_RAW)
.build())
.setResultCallback(new ResultCallback<DataSourcesResult>() {
@Override
public void onResult(DataSourcesResult dataSourcesResult) {
for (DataSource dataSource : dataSourcesResult.getDataSources()) {
if (DataType.TYPE_DISTANCE_CUMULATIVE.equals(dataSource.getDataType())) {
registerFitnessDataListener(dataSource, DataType.TYPE_DISTANCE_CUMULATIVE);
}
}
}
});
}
private void registerFitnessDataListener(DataSource dataSource, DataType dataType) {
mListener = new OnDataPointListener() {
@Override
public void onDataPoint(DataPoint dataPoint) {
for (final Field field : dataPoint.getDataType().getFields()) {
final Value val = dataPoint.getValue(field);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity(), "Field: " + field.getName() + " Value: " + val, Toast.LENGTH_SHORT).show();
}
});
}
}
};
Fitness.SensorsApi.add(
mClient,
new SensorRequest.Builder()
.setDataSource(dataSource)
.setDataType(dataType)
.setSamplingRate(3, TimeUnit.SECONDS)
.build(),
mListener)
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
if (status.isSuccess()) {
Log.i(TAG, "Listener registered!");
} else {
Log.i(TAG, "Listener not registered.");
}
}
});
}