Google fit history API无法检索数据集?

时间:2016-01-26 12:53:40

标签: java android google-api google-fit

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

  1. 我一直收到错误"插入数据集时出现问题。"在我的登录中没有别的东西出现后,我有点困惑为什么?

  2. 此外这似乎很有气质,有时它会起作用,并显示7个数据集随机数字(不是我的步数)所以我的第二个问题是我如何才能让它显示在今天?#?

  3. 验证

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

2 个答案:

答案 0 :(得分:0)

使用以下代码获取今天的步骤:

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;

答案 1 :(得分:0)

有时,我们还希望在特定时间范围内获取数据步骤,在这种情况下,这就是原因。

有一些可能的原因:

1)您是否订阅了此类数据?

2)您的应用与Google服务无法正常连接。您是否从Google开发控制台创建了OAuth客户端ID?这是谷歌连接到GG Fit服务的强制性指令(请注意,如果您在同一台计算机上克隆另一个应用程序,则需要重新创建另一个OAuth客户端ID,还需要另外一个2个独立帐户,一个用于登录Google开发控制台以创建OAuth客户端ID,另一个用于在启动应用程序后登录,它将要求您登录以接受其权限,...不确定原因是什么,但它会起作用)< / p>

注意:您可以在设备中搜索Google设置(设置 - &gt; Google),在这里您可以找到连接到Google服务的应用(包括GG Fit服务)。我建议您断开所有连接并删除OAuth客户端ID,您的应用,然后重新创建所有这些!

Mttdat。