我的应用正在从 Google Fit 读取体重数据。数据是由 Withings 和我自己的应用程序插入的。但这在我调用时没有任何区别dataSet.getDataSource().getAppPackageName()
,因为它总是返回com.google.android.gms
。所以我没有机会知道数据来自哪里。谷歌在这篇文章中描述了如何获取数据源的信息:https ://developers.google.com/fit/android/data-attribution不幸的是这对我来说完全没用。
我正在使用 Google Play Services 8.3.0,使用 Android 4.3、4.4.2 和 6.0.1 进行了测试。
任何人都可以确认相同的行为吗?还是我做错了什么?任何反馈表示赞赏。
public void connect(final Activity activity) {
client = new GoogleApiClient.Builder(activity)
.addApi(Fitness.HISTORY_API)
.addApi(Fitness.CONFIG_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
.addScope(new Scope(Scopes.FITNESS_BODY_READ_WRITE))
.build();
client.connect();
}
public DataReadResult readWeightValues(final Date startDate, final Date endDate) {
final DataReadRequest readRequest = new DataReadRequest.Builder()
.enableServerQueries()
.setTimeRange(startDate.getTime(), endDate.getTime(), TimeUnit.MILLISECONDS)
.read(DataType.TYPE_WEIGHT)
.build();
return Fitness.HistoryApi.readData(client, readRequest).await(1, TimeUnit.MINUTES);
}
public void examineWeightValues(final DataReadResult dataReadResult) {
if ((dataReadResult != null) && dataReadResult.getStatus().isSuccess()) {
if (!dataReadResult.getBuckets().isEmpty()) {
for (final Bucket bucket : dataReadResult.getBuckets()) {
final List<DataSet> dataSets = bucket.getDataSets();
for (final DataSet dataSet : dataSets) {
Log.i("=====>", dataSet.getDataSource().getAppPackageName());
}
}
}
if (!dataReadResult.getDataSets().isEmpty()) {
for (final DataSet dataSet : dataReadResult.getDataSets()) {
Log.i("=====>", dataSet.getDataSource().getAppPackageName());
}
}
}
}
public Status insertWeightValue(final Context context, final Date date, final float weightKg) {
final DataSource dataSource = new DataSource.Builder()
.setAppPackageName(context.getApplicationContext().getPackageName())
// already tried setAppPackageName(context) too
.setName("com.mycompany.myapp")
.setDataType(DataType.TYPE_WEIGHT)
.setType(DataSource.TYPE_RAW)
.build();
final DataSet dataSet = DataSet.create(dataSource);
final DataPoint dataPoint = dataSet.createDataPoint();
dataPoint.setTimestamp(date.getTime(), TimeUnit.MILLISECONDS);
dataPoint.getValue(Field.FIELD_WEIGHT).setFloat(weightKg);
dataSet.add(dataPoint);
return Fitness.HistoryApi.insertData(client, dataSet).await(1, TimeUnit.MINUTES);
}