我正在开发app fitness应用程序,为此我使用了google fit api。到目前为止,我成功地取得了步骤计数,距离,但我无法得到卡路里支出。
提前谢谢
最佳答案
您需要先设置用户的体重和身高。消耗的卡路里是用这个信息计算出来的。
这些是我用来做这件事的方法。
(mclient是一个googleapclient实例)
public static void saveUserHeight(int heightCentimiters) {
// to post data
float height = ((float) heightCentimiters) / 100.0f;
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.DAY_OF_YEAR, -1);
long startTime = cal.getTimeInMillis();
DataSet heightDataSet = createDataForRequest(
DataType.TYPE_HEIGHT, // for height, it would be DataType.TYPE_HEIGHT
DataSource.TYPE_RAW,
height, // weight in kgs
startTime, // start time
endTime, // end time
TimeUnit.MILLISECONDS // Time Unit, for example, TimeUnit.MILLISECONDS
);
com.google.android.gms.common.api.Status heightInsertStatus =
Fitness.HistoryApi.insertData(mClient, heightDataSet)
.await(1, TimeUnit.MINUTES);
}
public static void saveUserWeight(float weight) {
// to post data
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.DAY_OF_YEAR, -1);
long startTime = cal.getTimeInMillis();
DataSet weightDataSet = createDataForRequest(
DataType.TYPE_WEIGHT, // for height, it would be DataType.TYPE_HEIGHT
DataSource.TYPE_RAW,
weight, // weight in kgs
startTime, // start time
endTime, // end time
TimeUnit.MILLISECONDS // Time Unit, for example, TimeUnit.MILLISECONDS
);
com.google.android.gms.common.api.Status weightInsertStatus =
Fitness.HistoryApi.insertData(mClient, weightDataSet)
.await(1, TimeUnit.MINUTES);
}
public static DataSet createDataForRequest(DataType dataType,
int dataSourceType,
Object values,
long startTime,
long endTime,
TimeUnit timeUnit) {
DataSource dataSource = new DataSource.Builder()
.setAppPackageName(appContext)
.setDataType(dataType)
.setType(dataSourceType)
.build();
DataSet dataSet = DataSet.create(dataSource);
DataPoint dataPoint = dataSet.createDataPoint().setTimeInterval(startTime, endTime, timeUnit);
if (values instanceof Integer) {
dataPoint = dataPoint.setIntValues((Integer) values);
} else {
dataPoint = dataPoint.setFloatValues((Float) values);
}
dataSet.add(dataPoint);
return dataSet;
}