Google Fit Android API可保存所有设备的数据,但无法查询不同设备的数据

问题描述 投票:0回答:1

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

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

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

我看了this question,但我已经实施了他们的建议......

看下面的代码......

谢谢你,约书亚


My Google Api Client is built like this

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

Insert pushups code:

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();
        }
    }

Update pushups log code:

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);
        }
    ...
}
android google-api google-fit google-fit-sdk android-googleapiclient
1个回答
0
投票

我有类似的问题,我能够通过添加documentation中提到的订阅来检索数据。

要从健身历史中读取数据:

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

添加subscription

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();
© www.soinside.com 2019 - 2024. All rights reserved.