Google 拟合历史 API 不会检索数据集?

Google fit history API won't retrieve dataset?

我目前正在尝试通过我的应用程序显示今天的当前步骤。我在下面有以下代码,大部分时间都可以进行身份​​验证。我也已将 SHA1 证书添加到开发人员控制台。

  1. 我在日志中不断收到错误 "There was a problem inserting the dataset.",此后没有出现任何其他错误,我有点困惑为什么?

  2. 而且这似乎是喜怒无常的,有时它会工作并显示 7 个随机数字的数据集(不是我的步数)所以我的第二个问题是如何让它显示今天的?

身份验证

private void buildFitnessClient() {
    if (mClient == null) {
        mClient = new GoogleApiClient.Builder(this)
                .addApi(Fitness.HISTORY_API)
                .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ))
                .addConnectionCallbacks(
                        new GoogleApiClient.ConnectionCallbacks() {
                            @Override
                            public void onConnected(Bundle bundle) {
                                Log.i(TAG, "Connected!!!");
                                // Now you can make calls to the Fitness APIs.
                                new InsertAndVerifyDataTask().execute();


                            }

                            @Override
                            public void onConnectionSuspended(int i) {
                                // If your connection to the sensor gets lost at some point,
                                // you'll be able to determine the reason and react to it here.
                                if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
                                    Log.i(TAG, "Connection lost.  Cause: Network Lost.");
                                    Toast.makeText(getBaseContext(), "Connection lost.  Cause: Network Lost.", Toast.LENGTH_LONG).show();

                                } else if (i
                                        == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
                                    Log.i(TAG,
                                            "Connection lost.  Reason: Service Disconnected");
                                }
                            }
                        }
                )
                .enableAutoManage(this, 0, new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(ConnectionResult result) {
                        Log.i(TAG, "Google Play services connection failed. Cause: " +
                                result.toString());
                        Toast.makeText(getBaseContext(), "Google Play services connection failed. Cause: " +
                                result.toString(), Toast.LENGTH_LONG).show();

                    }
                })
                .build();
    }


}

我认为问题出在哪里。

private class InsertAndVerifyDataTask extends AsyncTask<Void, Void, Void> {
    protected Void doInBackground(Void... params) {
        //First, create a new dataset and insertion request.
        DataSet dataSet = insertFitnessData();

        // [START insert_dataset]
        // Then, invoke the History API to insert the data and await the result, which is
        // possible here because of the {@link AsyncTask}. Always include a timeout when calling
        // await() to prevent hanging that can occur from the service being shutdown because
        // of low memory or other conditions.
        Log.i(TAG, "Inserting the dataset in the History API");

        com.google.android.gms.common.api.Status insertStatus =
                Fitness.HistoryApi.insertData(mClient, dataSet)
                        .await(1, TimeUnit.MINUTES);

        // Before querying the data, check to see if the insertion succeeded.
        if (!insertStatus.isSuccess()) {
            Log.i(TAG, "There was a problem inserting the dataset.");
            return null;
        }

        // At this point, the data has been inserted and can be read.
        Log.i(TAG, "Data insert was successful!");
        // [END insert_dataset]

        // Begin by creating the query.
        DataReadRequest readRequest = queryFitnessData();

        // [START read_dataset]
        // Invoke the History API to fetch the data with the query and await the result of
        // the read request.
        DataReadResult dataReadResult =
                Fitness.HistoryApi.readData(mClient, readRequest).await(1, TimeUnit.MINUTES);
        // [END read_dataset]

        // For the sake of the sample, we'll print the data so we can see what we just added.
        // In general, logging fitness information should be avoided for privacy reasons.
        printData(dataReadResult);

        return null;
    }
}


private DataSet insertFitnessData() {
    Log.i(TAG, "Creating a new data insert request");

    // [START build_insert_data_request]
    // Set a start and end time for our data, using a start time of 1 hour before this moment.
    Calendar cal = Calendar.getInstance();
    Date now = new Date();
    cal.setTime(now);
    long endTime = cal.getTimeInMillis();
    cal.add(Calendar.HOUR_OF_DAY, -1);
    long startTime = cal.getTimeInMillis();

    // Create a data source
    DataSource dataSource = new DataSource.Builder()
            .setAppPackageName(this)
            .setDataType(DataType.TYPE_STEP_COUNT_DELTA)
            .setName(TAG + " - step count")
            .setType(DataSource.TYPE_RAW)
            .build();

    // Create a data set
    int stepCountDelta = 1000;
    DataSet dataSet = DataSet.create(dataSource);
    // For each data point, specify a start time, end time, and the data value -- in this case,
    // the number of new steps.
    DataPoint dataPoint = dataSet.createDataPoint()
            .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS);

    dataPoint.getValue(Field.FIELD_STEPS).setInt(stepCountDelta);
    dataSet.add(dataPoint);
    // [END build_insert_data_request]

    return dataSet;
}

使用以下代码完成今天的步骤:

Calendar cal = Calendar.getInstance();
        Date now = new Date();
        cal.setTime(now);
        long endTime = cal.getTimeInMillis();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 00);
        long startTime = cal.getTimeInMillis();


        int steps = 0;
        DataSource ESTIMATED_STEP_DELTAS = new DataSource.Builder()
                .setDataType(DataType.TYPE_STEP_COUNT_DELTA)
                .setType(DataSource.TYPE_DERIVED)
                .setStreamName("estimated_steps")
                .setAppPackageName("com.google.android.gms").build();

        // fill result with just the steps from the start and end time of the present day
        PendingResult<DailyTotalResult> result = Fitness.HistoryApi.readDailyTotal(mClient, DataType.AGGREGATE_STEP_COUNT_DELTA);
        DailyTotalResult totalResult = result.await(60, TimeUnit.SECONDS);
        if (totalResult.getStatus().isSuccess()) {
            DataSet totalSet = totalResult.getTotal();
            steps = totalSet.isEmpty() ? -1 : totalSet.getDataPoints().get(0).getValue(Field.FIELD_STEPS).asInt();
        }

        s = String.valueOf(steps);

        DataReadRequest readRequest = queryFitnessData();

        DataReadResult dataReadResult =
                Fitness.HistoryApi.readData(mClient, readRequest).await(1, TimeUnit.MINUTES);
        feedItemList.clear();

        printData(dataReadResult);
        return null;

有时候我们也想获取特定时间范围内的数据step,这就是原因。

有一些可能的原因:

1) 您订阅过此类数据吗?

2) 您的应用无法与 google 服务正确连接。您是否从 Google 开发控制台创建了 OAuth 客户端 ID?这是 google 连接到其 GG Fit 服务的强制性说明(请注意,如果您在同一台计算机上克隆另一个应用程序,您需要重新创建另一个 OAuth 客户端 ID,并且您还需要做一件事需要 2 个单独的帐户,一个用于登录 Google 开发控制台以创建 OAuth 客户端 ID,一个用于在启动您的应用程序后登录,它会要求您登录以接受其许可,...不知道为什么是,但它会起作用)

注意:顺便说一句,您可以在设备中搜索有关 Google 的设置(设置 --> Google),在这里您可以找到哪个应用程序连接到 google 服务(包括 GG Fit 服务)。我建议您断开所有连接并删除 OAuth 客户端 ID、您的应用程序,然后重新创建所有这些!

Mttdat.