0

我正在创建一个记录俯卧撑的锻炼应用程序。我的目标是将数据与 Google Fit 集成,以便在设备之间或在用户获得新设备的情况下同步。

我已经成功地将数据插入到 Google Fit 中,然后可以查询它。它还显示在 Google Fit 网络应用程序上。

我的问题是,当我在我的 Nexus 7 上并尝试查询所有数据时,它只返回我的 Nexus 7 的数据,而不是我的中兴 Maven 和我的 Nexus 7。当我在我的中兴 Maven 上时,我尝试要查询所有数据,它只返回我的中兴 Maven 的数据,而不是我的 Nexus 7 和我的中兴 Maven。我希望它能够显示来自所有设备的所有数据。任何帮助,将不胜感激!

我看了这个问题,但我已经实施了他们的建议......

请参阅下面的代码...

谢谢,约书亚


我的 Google Api 客户端是这样构建的

new GoogleApiClient.Builder(activity)
          .addApi(Fitness.HISTORY_API)
          .addApi(Fitness.SESSIONS_API)
          .addScope(Fitness.SCOPE_ACTIVITY_READ_WRITE)
          .useDefaultAccount()
          .addConnectionCallbacks(...)
          .addOnConnectionFailedListener(...)
          .build();

插入俯卧撑代码:

private class InsertGoogleFitDataTask extends AsyncTask<WorkoutSet, Void, Boolean> {
        protected Boolean doInBackground (WorkoutSet... workoutSets) {
            DataSource dataSource = new DataSource.Builder().setAppPackageName(RootLogActivity.this)
                                                            .setDataType(DataType.TYPE_WORKOUT_EXERCISE)
                                                            .setName("Push Ups")
                                                            .setType(DataSource.TYPE_RAW)
                                                            .build();

            DataSet dataSet = DataSet.create(dataSource);
            for (WorkoutSet workoutSet : workoutSets) {
                long startTime = workoutSet.getTimeInterval().getStartMillis();
                long endTime = workoutSet.getTimeInterval().getEndMillis();
                DataPoint dataPoint = DataPoint.create(dataSource);
                int duration = (int) (endTime - startTime);
                dataPoint.setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS);
                dataPoint.setTimestamp(startTime + (endTime - startTime) / 2, TimeUnit.MILLISECONDS);
                dataPoint.getValue(Field.FIELD_EXERCISE).setString(WorkoutExercises.PUSHUP);
                dataPoint.getValue(Field.FIELD_REPETITIONS).setInt(workoutSet.getTotalCount());
                dataPoint.getValue(Field.FIELD_DURATION).setInt(duration);
                dataPoint.getValue(Field.FIELD_RESISTANCE_TYPE).setInt(Field.RESISTANCE_TYPE_BODY);
                dataPoint.getValue(Field.FIELD_RESISTANCE).setFloat(0);
                dataSet.add(dataPoint);
            }
            Session session = new Session.Builder().setStartTime(workoutSets[0].getTimeInterval().getStartMillis(), TimeUnit.MILLISECONDS)
                                                   .setEndTime(workoutSets[0].getTimeInterval().getEndMillis(), TimeUnit.MILLISECONDS)
                                                   .setActivity(FitnessActivities.OTHER)
                                                   .build();
            SessionInsertRequest sessionInsertRequest = new SessionInsertRequest.Builder().addDataSet(dataSet).setSession(session).build();
            com.google.android.gms.common.api.Status insertStatus = Fitness.SessionsApi.insertSession(GoogleUtils.getFitClient(), sessionInsertRequest)
                                                                                       .await(30, TimeUnit.SECONDS);
            return insertStatus.isSuccess();
        }

        @Override
        protected void onPostExecute (Boolean success) {
            Snackbar.make(tabLayout, String.format("Insert %ssuccessful", success ? "" : "un"), Snackbar.LENGTH_SHORT).show();
            new UpdateGoogleFitDataTask().execute();
        }
    }

更新俯卧撑日志代码:

private class UpdateGoogleFitDataTask extends AsyncTask<Void, Void, ArrayList<WorkoutMonth>> {
        protected ArrayList<WorkoutMonth> doInBackground (Void... ignored) {
            Calendar cal = Calendar.getInstance();
            Date     now = new Date();
            cal.setTime(now);
            long endTime = cal.getTimeInMillis();
            cal.clear();
            cal.set(2013, Calendar.DECEMBER, 6);    // This is the day before the first release version. There should be no data before.
            long startTime = cal.getTimeInMillis();

            DataSource dataSource = new DataSource.Builder().setAppPackageName(RootLogActivity.this)
                                                            .setDataType(DataType.TYPE_WORKOUT_EXERCISE)
                                                            .setName("Push Ups")
                                                            .setType(DataSource.TYPE_RAW)
                                                            .build();

            final DataReadRequest dataReadRequest = new DataReadRequest.Builder().read(dataSource)
                                                                                 .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
                                                                                 .enableServerQueries()
                                                                                 .build();

            SessionReadRequest sessionReadRequest = new SessionReadRequest.Builder().readSessionsFromAllApps()
                                                                                    .enableServerQueries()
                                                                                    .read(dataSource)
                                                                                    .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
                                                                                    .build();
            SessionReadResult dataReadResult = Fitness.SessionsApi.readSession(GoogleUtils.getFitClient(), sessionReadRequest)
                                                                  .await(1, TimeUnit.MINUTES);

            ArrayList<DataSet> filteredDataSets = new ArrayList<>();
            for (Session session : dataReadResult.getSessions()) {
                for (DataSet dataSet : dataReadResult.getDataSet(session)) {
                    dumpDataSet(dataSet);
                    if (!dataSet.getDataType().equals(DataType.TYPE_WORKOUT_EXERCISE)) { continue; }
                    filteredDataSets.add(dataSet);
                }
            }
            return WorkoutMonth.createMonthsFromDataSets(filteredDataSets);
        }
    ...
}
4

1 回答 1

-1

我遇到了类似的问题,我可以通过添加文档中提到的订阅来检索数据。

从健身历史中读取数据:

  1. 为您要记录的每种健身数据类型创建订阅。这使您的应用程序能够与来自其他设备的数据同步,并且还允许在设备上被动记录数据。
  2. 创建 DataReadRequest 实例

添加订阅

Fitness.getRecordingClient(this, GoogleSignIn.getLastSignedInAccount(this))
        .subscribe(DataType.TYPE_STEP_COUNT_DELTA)
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.i(TAG, "Successfully subscribed!");
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.i(TAG, "There was a problem subscribing.");
            }
        });

订阅激活后,您可以使用 Fitness api 读取相应数据

// Setting a start and end date using a range of 1 week before this moment.
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.WEEK_OF_YEAR, -1);
long startTime = cal.getTimeInMillis();

java.text.DateFormat dateFormat = getDateInstance();
Log.i(TAG, "Range Start: " + dateFormat.format(startTime));
Log.i(TAG, "Range End: " + dateFormat.format(endTime));

DataReadRequest readRequest =
    new DataReadRequest.Builder()
        // The data request can specify multiple data types to return, effectively
        // combining multiple data queries into one call.
        // In this example, it's very unlikely that the request is for several hundred
        // datapoints each consisting of a few steps and a timestamp.  The more likely
        // scenario is wanting to see how many steps were walked per day, for 7 days.
        .aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
        // Analogous to a "Group By" in SQL, defines how data should be aggregated.
        // bucketByTime allows for a time span, whereas bucketBySession would allow
        // bucketing by "sessions", which would need to be defined in code.
        .bucketByTime(1, TimeUnit.DAYS)
        .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
        .build();
于 2019-03-14T13:05:18.143 回答