2

I'm trying to implement Google Fit into my app, but I'm having trouble with the permission to store heart rate bpm datapoints. At first I only tried to insert activity, speed, distance and step rate data and that worked. But as soon as I added the heart rate bpm permission and datapoints I got an error 5000 from the api.

These are the fitness permissions that I request:

FitnessOptions.builder()
.addDataType(DataType.TYPE_ACTIVITY_SEGMENT, FitnessOptions.ACCESS_WRITE)
.addDataType(DataType.TYPE_SPEED, FitnessOptions.ACCESS_WRITE)
.addDataType(DataType.TYPE_DISTANCE_CUMULATIVE, FitnessOptions.ACCESS_WRITE)
.addDataType(DataType.TYPE_STEP_COUNT_CUMULATIVE, FitnessOptions.ACCESS_WRITE)
.addDataType(DataType.TYPE_HEART_RATE_BPM, FitnessOptions.ACCESS_WRITE)
.build();

Then when I'm trying to store a DataSet with DataType TYPE_HEART_RATE_BPM using the sessions api I the the error 5000.

I've also tried to completeley remove the permission of my app in the Google Fit app and then add the permission again, but I'm still receiving the error. Is there maybe an additional permission required to store heart rate data? Or is it only allowed to read heart rate data?

TheNetStriker
  • 67
  • 1
  • 5
  • Have you tried to check this [SO post](https://stackoverflow.com/questions/38255110/google-fit-authorization-bugs-with-5005-5000-and-5015-errors-on-watchface-w) about the Google Fit authorization bugs? – MαπμQμαπkγVπ.0 Aug 29 '18 at 09:34
  • I followed the official guide for the newest api. The post uses the older method. My current guess is that the type TYPE_HEART_RATE_BPM is maybe only to read heart beat data from a fitness watch.I've tried if I can store hear rate data as AGGREGATE_HEART_RATE_SUMMARY with min, max, and average values and that worked. But it seams that this heart rate data is not displayed later in the Google Fit app. – TheNetStriker Aug 30 '18 at 10:30

1 Answers1

1

I have previously worked on getting the heart rate data using Google fit. Initially, I have faced the same issue. If you go through the documentation in the following link https://developers.google.com/android/reference/com/google/android/gms/fitness/data/DataType.html#TYPE_HEART_RATE_BPM

It is clearly mentioned that you need to get BODY_SENSORS permission

"Registering to, or subscribing to data of this type requires BODY_SENSORS"

If the user doesn't grant the permission for BODY_SENSORS, then we will be getting the error as we won't be able to access or insert Heart rate data.

You may use the below code to request the user for granting permission

ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.BODY_SENSORS},
                            BODY_SENSOR_PERMISSION_REQUEST_CODE);

You can check if the user has granted permission in the 'onRequestPermissionsResult' callback and then request for Heart rate data.

Adding sample code as requested.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{android.Manifest.permission.BODY_SENSORS},
                        BODY_SENSOR_PERMISSION_REQUEST_CODE);
            }



private class InsertAndVerifyDataTask extends AsyncTask<Void, Void, Void> {
        protected Void doInBackground(Void... params) {
            // Create a new dataset and insertion request.
            DataSet dataSet = insertHeartData();
            // [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.
            com.google.android.gms.common.api.Status insertStatus =
                    Fitness.HistoryApi.insertData(connectFit.returnClient(), dataSet)
                            .await(1, TimeUnit.MINUTES);
            // Before querying the data, check to see if the insertion succeeded.
            if (!insertStatus.isSuccess()) {
                return null;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            Toast.makeText(MainActivity.this, "Added", Toast.LENGTH_SHORT).show();
        }
    }

private DataSet insertHeartData() {
        // [START build_insert_data_request]

        try {
            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_HEART_RATE_BPM)
                    .setStreamName(" - heart count")
                    .setType(DataSource.TYPE_DERIVED)
                    .build();
            // Create a data set
            float hearRate = Float.parseFloat(((EditText) (findViewById(R.id.heartRate))).getText().toString().trim());
            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, MILLISECONDS);
            dataPoint.getValue(Field.FIELD_BPM).setFloat(hearRate);
            dataSet.add(dataPoint);
            // [END build_insert_data_request]
            return dataSet;
        } catch (Exception e) {
            return null;
        }
    }

This worked for me.

Anudeep
  • 1,520
  • 1
  • 19
  • 38
  • I've already tried with this permission, but I got the same error when uploading the data as far as i remember. Can you provide a code sample on how you built and uploaded the dataset? – TheNetStriker Aug 31 '18 at 08:00
  • Thanks for the code. For some reason I was now able to upload the heart rate data, even without the body sensor right. But now I see that the heart rate data isn't displayed in the Google Fit app. (Neither in the fitness session nor in the heart rate tab) Any ideas on how this works? – TheNetStriker Sep 05 '18 at 09:58