无法将水合作用数据插入 Google Fit

Cannot insert hydration data to Google Fit

我正在尝试将 hydration 数据插入 Google Fit。但是我无法插入数据。

这是我的代码:

BuildFitnessClient:

private void buildFitnessClient() {
    Log.w("Fit","inside buildFitness");
    // Create the Google API Client
    if (mClient == null) {
        mClient = new GoogleApiClient.Builder(this)
                .addApi(Fitness.HISTORY_API)
                .addApi(Fitness.SESSIONS_API)
                //.addScope(new Scope(Scopes.FITNESS_LOCATION_READ_WRITE))
                .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
                .addConnectionCallbacks(
                        new GoogleApiClient.ConnectionCallbacks() {
                            @Override
                            public void onConnected(Bundle bundle) {
                                Log.i(TAG, "Connected!!!");
                                // Now you can make calls to the Fitness APIs.  What to do?
                                // Play with some sessions!!
                                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.");
                                } 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());
                        Snackbar.make(
                                DeviceControlActivity.this.findViewById(R.id.gatt_services),
                                "Exception while connecting to Google Play services: " +
                                        result.getErrorMessage(),
                                Snackbar.LENGTH_INDEFINITE).show();
                    }
                })
                .build();
    }
}

插入和验证数据:

private class InsertAndVerifyDataTask extends AsyncTask<Void, Void, Void> {
    protected Void doInBackground(Void... params) {
        // 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.");
        Log.w("Fit", "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.");
            Log.w("Fit", "Error inserting data");
            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_HYDRATION)
            .setStreamName(TAG + " - waterConsumed")
            .setType(DataSource.TYPE_RAW)
            .build();

    // Create a data set
    float waterConsumed = 0.3f;
    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 hydration = DataPoint.create(dataSource);
    hydration.setTimestamp(cal.getTimeInMillis(), TimeUnit.MILLISECONDS);
    hydration.getValue(Field.FIELD_VOLUME).setFloat(waterConsumed);
    dataSet.add(hydration);
    // [END build_insert_data_request]

    return dataSet;
}

目前我只是尝试先上传数据。查询数据的部分我都注释掉了

另外,当我第一次插入数据时,我返回的是插入失败的状态,但是当我再次尝试插入时并没有发生这种情况。 您可以在此处查看日志消息:

     06-30 00:09:21.416 10294-10294/com.polkapolka.bluetooth.le I/DeviceControlActivity: Connected!!!
    06-30 00:09:21.422 10294-12719/com.polkapolka.bluetooth.le I/DeviceControlActivity: Creating a new data insert request.
    06-30 00:09:21.457 10294-12719/com.polkapolka.bluetooth.le I/DeviceControlActivity: Inserting the dataset in the History API.
    06-30 00:09:21.457 10294-12719/com.polkapolka.bluetooth.le W/Fit: Inserting the dataset in the HISTORY api
    06-30 00:09:22.929 10294-12719/com.polkapolka.bluetooth.le I/DeviceControlActivity: There was a problem inserting the dataset.
    06-30 00:09:22.929 10294-12719/com.polkapolka.bluetooth.le W/Fit: Error inserting data
    06-30 00:09:40.164 10294-10294/com.polkapolka.bluetooth.le D/ViewRootImpl: doProcessInputEvents ViewRoot{81b6602 com.polkapolka.bluetooth.le/com.polkapolka.bluetooth.le.DeviceControlActivity,ident = 1}
    06-30 00:09:40.164 10294-10294/com.polkapolka.bluetooth.le D/View: Touch up dispatch to android.widget.Button{f043f11 VFED..C.. ...P.... 453,0-645,144 #7f0c0091 app:id/btn_fit}, event = MotionEvent { action=ACTION_UP, actionButton=0, id[0]=0, x[0]=40.51526, y[0]=64.24573, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=150185425, downTime=150185381, deviceId=3, source=0x1002 }
    06-30 00:09:40.164 10294-10294/com.polkapolka.bluetooth.le D/SettingsInterface:  from settings cache , name = sound_effects_enabled , value = 1
    06-30 00:09:40.164 10294-10294/com.polkapolka.bluetooth.le W/Fit: calling buildFitness
    06-30 00:09:40.164 10294-10294/com.polkapolka.bluetooth.le W/Fit: inside buildFitness
    06-30 00:10:13.225 10294-10294/com.polkapolka.bluetooth.le D/ViewRootImpl: doProcessInputEvents ViewRoot{81b6602 com.polkapolka.bluetooth.le/com.polkapolka.bluetooth.le.DeviceControlActivity,ident = 1}
    06-30 00:10:13.225 10294-10294/com.polkapolka.bluetooth.le D/View: Touch up dispatch to android.widget.Button{f043f11 VFED..C.. ...P.... 453,0-645,144 #7f0c0091 app:id/btn_fit}, event = MotionEvent { action=ACTION_UP, actionButton=0, id[0]=0, x[0]=89.46991, y[0]=74.24048, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=150218486, downTime=150218460, deviceId=3, source=0x1002 }
    06-30 00:10:13.226 10294-10294/com.polkapolka.bluetooth.le D/SettingsInterface:  from settings cache , name = sound_effects_enabled , value = 1
    06-30 00:10:13.226 10294-10294/com.polkapolka.bluetooth.le W/Fit: calling buildFitness
    06-30 00:10:13.226 10294-10294/com.polkapolka.bluetooth.le W/Fit: inside buildFitness
06-30 00:20:03.346 10294-10294/com.polkapolka.bluetooth.le V/InputMethodManager: START INPUT: android.widget.NumberPicker$CustomEditText{1734323 VFED..CL. .F...... 0,38-192,111 #102038b android:id/numberpicker_input} ic=com.android.internal.widget.EditableInputConnection@347dd7a tba=android.view.inputmethod.EditorInfo@170a92b controlFlags=#100
06-30 00:20:03.378 10294-10294/com.polkapolka.bluetooth.le I/Activity: [AppLaunch] activity.onPause +
06-30 00:20:03.413 10294-10294/com.polkapolka.bluetooth.le I/Activity: [AppLaunch] activity.onPause -

基本上,在第二次请求插入数据之后,它似乎根本没有进入 insertFitnessData()。

编辑 1: 我意识到我不需要每次都调用 BuildFitness() 方法。所以它在 onCreate() 期间只被调用一次,正如您在日志消息中看到的那样,它说 "connected" 以适应服务。

现在我在按钮 onclick() 上触发 InsertandVerifyDataTask 异步任务,每次数据插入失败时。

EDIT 2 我尝试按照他们的 github 页面中给出的步骤插入步骤数据并且有效。但是水合作用不是。

有人可以帮帮我吗?谢谢 :D

确保您已添加 new Scope(Scopes.FITNESS_NUTRITION_READ_WRITE) in requestScopes in GoogleSignInOptions.Builder. Datatype TYPE_HYDRATION belongs to the scope FITNESS_NUTRITION. The app also needs to be uninstalled and reinstalled to add the new scope to the account. You may check this