com.google.android.gms.fitness.data.DataSource Java Examples

The following examples show how to use com.google.android.gms.fitness.data.DataSource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HydrationHistory.java    From react-native-google-fit with MIT License 6 votes vote down vote up
public boolean save(ReadableArray hydrationArray) {
  DataSource hydrationSource = this.getDataSource();
  ArrayList<DataPoint> dataPoints = new ArrayList<DataPoint>();
  ArrayList<DataSet> dataSets = new ArrayList<DataSet>();
  for (int index = 0 ; index < hydrationArray.size() ; index++) {
    ReadableMap hydrationSample = hydrationArray.getMap(index);
    if (hydrationSample != null) {
      dataPoints.add(DataPoint.builder(hydrationSource)
        .setTimestamp((long) hydrationSample.getDouble("date"), TimeUnit.MILLISECONDS)
        .setField(Field.FIELD_VOLUME, (float) hydrationSample.getDouble("waterConsumed"))
        .build());
    }
    if (dataPoints.size() % MAX_DATAPOINTS_PER_SINGLE_REQUEST == 0) {
      // Be sure to limit each individual request to 1000 datapoints. Exceeding this limit could result in an error.
      // https://developers.google.com/fit/android/history#insert_data
      dataSets.add(DataSet.builder(hydrationSource).addAll(dataPoints).build());
      dataPoints.clear();
    }
  }
  if (dataPoints.size() > 0) {
    dataSets.add(DataSet.builder(hydrationSource).addAll(dataPoints).build());
  }
  new SaveDataHelper(dataSets, googleFitManager).execute();

  return true;
}
 
Example #2
Source File: BodyHistory.java    From react-native-google-fit with MIT License 6 votes vote down vote up
/**
 * This method creates a dataset object to be able to insert data in google fit
 * @param dataType DataType Fitness Data Type object
 * @param dataSourceType int Data Source Id. For example, DataSource.TYPE_RAW
 * @param value Object Values for the fitness data. They must be int or float
 * @param startTime long Time when the fitness activity started
 * @param endTime long Time when the fitness activity finished
 * @param timeUnit TimeUnit Time unit in which period is expressed
 * @return
 */
private DataSet createDataForRequest(DataType dataType, int dataSourceType, Double value,
                                     long startTime, long endTime, TimeUnit timeUnit) {
    DataSource dataSource = new DataSource.Builder()
            .setAppPackageName(GoogleFitPackage.PACKAGE_NAME)
            .setDataType(dataType)
            .setType(dataSourceType)
            .build();

    DataSet dataSet = DataSet.create(dataSource);
    DataPoint dataPoint = dataSet.createDataPoint().setTimeInterval(startTime, endTime, timeUnit);

    float f1 = Float.valueOf(value.toString());
    dataPoint = dataPoint.setFloatValues(f1);

    dataSet.add(dataPoint);

    return dataSet;
}
 
Example #3
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
@Override
public void onConnected(Bundle bundle) {
    DataSourcesRequest dataSourceRequest = new DataSourcesRequest.Builder()
            .setDataTypes( DataType.TYPE_STEP_COUNT_CUMULATIVE )
            .setDataSourceTypes( DataSource.TYPE_RAW )
            .build();

    ResultCallback<DataSourcesResult> dataSourcesResultCallback = new ResultCallback<DataSourcesResult>() {
        @Override
        public void onResult(DataSourcesResult dataSourcesResult) {
            for( DataSource dataSource : dataSourcesResult.getDataSources() ) {
                if( DataType.TYPE_STEP_COUNT_CUMULATIVE.equals( dataSource.getDataType() ) ) {
                    registerFitnessDataListener(dataSource, DataType.TYPE_STEP_COUNT_CUMULATIVE);
                }
            }
        }
    };

    Fitness.SensorsApi.findDataSources(mApiClient, dataSourceRequest)
            .setResultCallback(dataSourcesResultCallback);
}
 
Example #4
Source File: HeartrateHistory.java    From react-native-google-fit with MIT License 6 votes vote down vote up
/**
 * This method creates a dataset object to be able to insert data in google fit
 * @param dataType DataType Fitness Data Type object
 * @param dataSourceType int Data Source Id. For example, DataSource.TYPE_RAW
 * @param value Object Values for the fitness data. They must be int or float
 * @param startTime long Time when the fitness activity started
 * @param endTime long Time when the fitness activity finished
 * @param timeUnit TimeUnit Time unit in which period is expressed
 * @return
 */
private DataSet createDataForRequest(DataType dataType, int dataSourceType, Double value,
                                     long startTime, long endTime, TimeUnit timeUnit) {
    DataSource dataSource = new DataSource.Builder()
            .setAppPackageName(GoogleFitPackage.PACKAGE_NAME)
            .setDataType(dataType)
            .setType(dataSourceType)
            .build();

    DataSet dataSet = DataSet.create(dataSource);
    DataPoint dataPoint = dataSet.createDataPoint().setTimeInterval(startTime, endTime, timeUnit);

    float f1 = Float.valueOf(value.toString());
    dataPoint = dataPoint.setFloatValues(f1);

    dataSet.add(dataPoint);

    return dataSet;
}
 
Example #5
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
private void registerFitnessDataListener(DataSource dataSource, DataType dataType) {

        SensorRequest request = new SensorRequest.Builder()
                .setDataSource( dataSource )
                .setDataType( dataType )
                .setSamplingRate( 3, TimeUnit.SECONDS )
                .build();

        Fitness.SensorsApi.add(mApiClient, request, this)
                .setResultCallback(new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        if (status.isSuccess()) {
                            Log.e("GoogleFit", "SensorApi successfully added");
                        } else {
                            Log.e("GoogleFit", "adding status: " + status.getStatusMessage());
                        }
                    }
                });
    }
 
Example #6
Source File: StepCounter.java    From react-native-google-fit with MIT License 6 votes vote down vote up
public void findFitnessDataSources() {

        DataSourcesRequest dataSourceRequest = new DataSourcesRequest.Builder()
                .setDataTypes(DataType.TYPE_STEP_COUNT_DELTA, DataType.TYPE_STEP_COUNT_CUMULATIVE)
                .setDataSourceTypes( DataSource.TYPE_DERIVED)
                .build();

        ResultCallback<DataSourcesResult> dataSourcesResultCallback = new ResultCallback<DataSourcesResult>() {
            @Override
            public void onResult(DataSourcesResult dataSourcesResult) {
                for (DataSource dataSource : dataSourcesResult.getDataSources()) {
                    DataType type = dataSource.getDataType();

                    if (DataType.TYPE_STEP_COUNT_DELTA.equals(type)
                            || DataType.TYPE_STEP_COUNT_CUMULATIVE.equals(type)) {
                        Log.i(TAG, "Register Fitness Listener: " + type);
                        registerFitnessDataListener(dataSource, type);//DataType.TYPE_STEP_COUNT_DELTA);
                    }
                }
            }
        };

        Fitness.SensorsApi.findDataSources(googleFitManager.getGoogleApiClient(), dataSourceRequest)
                .setResultCallback(dataSourcesResultCallback);
    }
 
Example #7
Source File: StepCounter.java    From react-native-google-fit with MIT License 6 votes vote down vote up
private void registerFitnessDataListener(DataSource dataSource, DataType dataType) {

        SensorRequest request = new SensorRequest.Builder()
                .setDataSource(dataSource)
                .setDataType(dataType)
                .setSamplingRate(3, TimeUnit.SECONDS)
                .build();

        Fitness.SensorsApi.add(googleFitManager.getGoogleApiClient(), request, this)
                .setResultCallback(new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        if (status.isSuccess()) {
                            Log.i(TAG, "SensorApi successfully added");
                        }
                    }
                });
    }
 
Example #8
Source File: DataQueries.java    From GoogleFitExample with Apache License 2.0 6 votes vote down vote up
public static DataSet createActivityDataSet(long startTime, long endTime, String activityName, String packageName, Device device) {

        // Create a data source
        DataSource dataSource = new DataSource.Builder()
                .setAppPackageName(packageName)
                .setDevice(device)
                .setDataType(DataType.TYPE_ACTIVITY_SEGMENT)
                .setName(TAG + " - activity")
                .setType(DataSource.TYPE_RAW)
                .build();

        // Create a data set
        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 activityDataPoint = dataSet.createDataPoint()
                .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS);
        //dataPoint.getValue(Field.FIELD_STEPS).setInt(stepCountDelta); // Can't do this on an Activity Segment
        activityDataPoint.getValue(Field.FIELD_ACTIVITY).setActivity(activityName);
        dataSet.add(activityDataPoint);

        return dataSet;
    }
 
Example #9
Source File: DataQueries.java    From GoogleFitExample with Apache License 2.0 6 votes vote down vote up
/**
 * DataSets can only include one data type.
 *
 * @param startTime Start time for the activity in milliseconds
 * @param endTime End time for the activity in milliseconds
 * @param stepCountDelta Number of steps during the activity
 * @param packageName Package name for the app
 * @return Resulting DataSet
 */
public static DataSet createStepDeltaDataSet(long startTime, long endTime, int stepCountDelta, String packageName, Device device) {

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

    // Create a data set
    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); // Can't do this on an Activity Segment
    dataSet.add(dataPoint);

    return dataSet;
}
 
Example #10
Source File: DataQueries.java    From GoogleFitExample with Apache License 2.0 6 votes vote down vote up
/**
 * GET total estimated STEP_COUNT
 *
 * Retrieves an estimated step count.
 *
 */
public static DataReadRequest queryStepEstimate(long startTime, long endTime) {
    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();

    return new DataReadRequest.Builder()
            .aggregate(ESTIMATED_STEP_DELTAS, DataType.AGGREGATE_STEP_COUNT_DELTA)
            .bucketByTime(1, TimeUnit.DAYS)
            .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
            .enableServerQueries() // Used to retrieve data from cloud
            .build();
}
 
Example #11
Source File: GoogleFit.java    From cordova-plugin-googlefit with MIT License 5 votes vote down vote up
/**
 * Convert a DataSet into its JSON representation
 * @param dataSet
 * @return
 */
private JSONArray convertDatasetToJson(DataSet dataSet) {
    SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);

    JSONArray dataSet_JSON = new JSONArray();

    for (DataPoint dp : dataSet.getDataPoints()) {
        JSONObject dataPoint_JSON = new JSONObject();

        try {
            dataPoint_JSON.put("type", dp.getDataType().getName());
            DataSource dataSource = dp.getOriginalDataSource();
            String appPkgName = dataSource.getAppPackageName();
            dataPoint_JSON.put("source", appPkgName);
            dataPoint_JSON.put("start", dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
            dataPoint_JSON.put("end", dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)));

            JSONArray field_value_pairs = new JSONArray();

            for(Field field : dp.getDataType().getFields()) {
                JSONObject field_value_pair = new JSONObject();
                field_value_pair.put("field", field.getName());
                field_value_pair.put("value", dp.getValue(field));
                field_value_pairs.put(field_value_pair);
            }
            dataPoint_JSON.put("fields", field_value_pairs);

            dataSet_JSON.put(dataPoint_JSON);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return dataSet_JSON;
}
 
Example #12
Source File: GoogleFitSessionManager.java    From JayPS-AndroidApp with MIT License 5 votes vote down vote up
private DataSet createDataSource() {
    DataSource activitySegmentDataSource = new DataSource.Builder()
            .setAppPackageName(_context.getPackageName())
            .setDataType(DataType.TYPE_ACTIVITY_SEGMENT)
            .setName("PebbleBike-activity segments")
            .setType(DataSource.TYPE_RAW)
            .build();
    return DataSet.create(activitySegmentDataSource);
}
 
Example #13
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
private void updateStepDataOnGoogleFit() {
    //If two entries overlap, the new data is dropped when trying to insert. Instead, you need to use update
    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();

    DataSource dataSource = new DataSource.Builder()
            .setAppPackageName(this)
            .setDataType(DataType.TYPE_STEP_COUNT_DELTA)
            .setName("Step Count")
            .setType(DataSource.TYPE_RAW)
            .build();

    int stepCountDelta = 2000000;
    DataSet dataSet = DataSet.create(dataSource);

    DataPoint point = dataSet.createDataPoint()
            .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS);
    point.getValue(Field.FIELD_STEPS).setInt(stepCountDelta);
    dataSet.add(point);

    DataUpdateRequest updateRequest = new DataUpdateRequest.Builder().setDataSet(dataSet).setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS).build();
    Fitness.HistoryApi.updateData(mGoogleApiClient, updateRequest).await(1, TimeUnit.MINUTES);
}
 
Example #14
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
private void addStepDataToGoogleFit() {
    //Adds steps spread out evenly from start time to end time
    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();

    DataSource dataSource = new DataSource.Builder()
            .setAppPackageName(this)
            .setDataType(DataType.TYPE_STEP_COUNT_DELTA)
            .setName("Step Count")
            .setType(DataSource.TYPE_RAW)
            .build();

    int stepCountDelta = 1000000;
    DataSet dataSet = DataSet.create(dataSource);

    DataPoint point = dataSet.createDataPoint()
            .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS);
    point.getValue(Field.FIELD_STEPS).setInt(stepCountDelta);
    dataSet.add(point);

    Status status = Fitness.HistoryApi.insertData(mGoogleApiClient, dataSet).await(1, TimeUnit.MINUTES);

    if (!status.isSuccess()) {
        Log.e( "History", "Problem with inserting data: " + status.getStatusMessage());
    } else {
        Log.e( "History", "data inserted" );
    }
}
 
Example #15
Source File: GoogleFit.java    From OpenFit with MIT License 5 votes vote down vote up
private boolean insertHeartRate () {
    boolean success = true;
    if(heartRateList != null) {
        Log.d(LOG_TAG, "write heartRate");

        DataSource bpmDataSource = new DataSource.Builder()
        .setAppPackageName("com.solderbyte.openfit")
        .setDataType(DataType.TYPE_HEART_RATE_BPM)
        .setName("Open Fit - heartrate data")
        .setType(DataSource.TYPE_RAW)
        .build();

        for(int i = 0; i < heartRateList.size(); i++) {
            long timeStamp = heartRateList.get(i).getTimeStamp();
            float bpm = (float) heartRateList.get(i).getHeartRate();
            Calendar cal = Calendar.getInstance();
            Date startDate = new Date(timeStamp);
            cal.setTime(startDate);
            cal.add(Calendar.SECOND, 1);
            Date endDate = new Date(cal.getTimeInMillis());

            DataSet dBPM = DataSet.create(bpmDataSource);
            DataPoint pBPM = dBPM.createDataPoint().setTimeInterval(startDate.getTime(), endDate.getTime(), TimeUnit.MILLISECONDS);
            pBPM = pBPM.setFloatValues(bpm);
            dBPM.add(pBPM);

            com.google.android.gms.common.api.Status insertStatusBPM = Fitness.HistoryApi.insertData(mClient, dBPM).await(1, TimeUnit.MINUTES);
            if(!insertStatusBPM.isSuccess()) {
                success &= false;
                Log.d(LOG_TAG, "Profile data: There was a problem inserting the session");
            }
            else {
                success &= true;
                Log.d(LOG_TAG, "Profile data inserted: " + insertStatusBPM);
            }
        }
    }
    return success;
}
 
Example #16
Source File: GoogleFit.java    From cordova-plugin-googlefit with MIT License 5 votes vote down vote up
/**
 * Convert a DataSet into its JSON representation
 * @param dataSet
 * @return
 */
private JSONArray convertDatasetToJson(DataSet dataSet) {
    SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);

    JSONArray dataSet_JSON = new JSONArray();

    for (DataPoint dp : dataSet.getDataPoints()) {
        JSONObject dataPoint_JSON = new JSONObject();

        try {
            dataPoint_JSON.put("type", dp.getDataType().getName());
            DataSource dataSource = dp.getOriginalDataSource();
            String appPkgName = dataSource.getAppPackageName();
            dataPoint_JSON.put("source", appPkgName);
            dataPoint_JSON.put("start", dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
            dataPoint_JSON.put("end", dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)));

            JSONArray field_value_pairs = new JSONArray();

            for(Field field : dp.getDataType().getFields()) {
                JSONObject field_value_pair = new JSONObject();
                field_value_pair.put("field", field.getName());
                field_value_pair.put("value", dp.getValue(field));
                field_value_pairs.put(field_value_pair);
            }
            dataPoint_JSON.put("fields", field_value_pairs);

            dataSet_JSON.put(dataPoint_JSON);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return dataSet_JSON;
}
 
Example #17
Source File: CalorieHistory.java    From react-native-google-fit with MIT License 5 votes vote down vote up
/**
 * This method creates a dataset object to be able to insert data in google fit
 *
 * @param dataType       DataType Fitness Data Type object
 * @param dataSourceType int Data Source Id. For example, DataSource.TYPE_RAW
 * @param values         Object Values for the fitness data. They must be HashMap
 * @param mealType       int Value of enum. For example Field.MEAL_TYPE_SNACK
 * @param name           String Dish name. For example "banana"
 * @param startTime      long Time when the fitness activity started
 * @param endTime        long Time when the fitness activity finished
 * @param timeUnit       TimeUnit Time unit in which period is expressed
 * @return
 */
private DataSet createDataForRequest(DataType dataType, int dataSourceType,
                                     HashMap<String, Object> values, int mealType, String name,
                                     long startTime, long endTime, TimeUnit timeUnit) {

    DataSource dataSource = new DataSource.Builder()
            .setAppPackageName(GoogleFitPackage.PACKAGE_NAME)
            .setDataType(dataType)
            .setType(dataSourceType)
            .build();

    DataSet dataSet = DataSet.create(dataSource);
    DataPoint dataPoint = dataSet.createDataPoint().setTimeInterval(startTime, endTime, timeUnit);

    dataPoint.getValue(Field.FIELD_FOOD_ITEM).setString(name);
    dataPoint.getValue(Field.FIELD_MEAL_TYPE).setInt(mealType);
    for (String key : values.keySet()) {
        Float value = Float.valueOf(values.get(key).toString());

        if (value > 0) {
            dataPoint.getValue(Field.FIELD_NUTRIENTS).setKeyValue(key, value);
        }
    }

    dataSet.add(dataPoint);

    return dataSet;
}
 
Example #18
Source File: CalorieHistory.java    From react-native-google-fit with MIT License 5 votes vote down vote up
public boolean saveFood(ReadableMap foodSample) {
    this.FoodDataSet = createDataForRequest(
            DataType.TYPE_NUTRITION,    // for height, it would be DataType.TYPE_HEIGHT
            DataSource.TYPE_RAW,
            foodSample.getMap("nutrients").toHashMap(),
            foodSample.getInt("mealType"),                  // meal type
            foodSample.getString("foodName"),               // food name
            (long)foodSample.getDouble("date"),             // start time
            (long)foodSample.getDouble("date"),             // end time
            TimeUnit.MILLISECONDS                // Time Unit, for example, TimeUnit.MILLISECONDS
    );
    new CalorieHistory.InsertAndVerifyDataTask(this.FoodDataSet).execute();

    return true;
}
 
Example #19
Source File: HeartrateHistory.java    From react-native-google-fit with MIT License 5 votes vote down vote up
public boolean save(ReadableMap sample) {
    // TODO: how to save blood pressure?

    this.Dataset = createDataForRequest(
            this.dataType,    // for heart rate, it would be DataType.TYPE_HEART_RATE_BPM
            DataSource.TYPE_RAW,
            sample.getDouble("value"),                  // heart rate in bmp
            (long)sample.getDouble("date"),              // start time
            (long)sample.getDouble("date"),                // end time
            TimeUnit.MILLISECONDS                // Time Unit, for example, TimeUnit.MILLISECONDS
    );
    new InsertAndVerifyDataTask(this.Dataset).execute();

    return true;
}
 
Example #20
Source File: BodyHistory.java    From react-native-google-fit with MIT License 5 votes vote down vote up
public boolean save(ReadableMap sample) {
    this.Dataset = createDataForRequest(
            this.dataType,    // for height, it would be DataType.TYPE_HEIGHT
            DataSource.TYPE_RAW,
            sample.getDouble("value"),                  // weight in kgs, height in metrs
            (long)sample.getDouble("date"),              // start time
            (long)sample.getDouble("date"),                // end time
            TimeUnit.MILLISECONDS                // Time Unit, for example, TimeUnit.MILLISECONDS
    );
    new InsertAndVerifyDataTask(this.Dataset).execute();

    return true;
}
 
Example #21
Source File: HydrationHistory.java    From react-native-google-fit with MIT License 5 votes vote down vote up
private DataSource getDataSource() {
  return new DataSource.Builder()
    .setAppPackageName(GoogleFitPackage.PACKAGE_NAME)
    .setDataType(this.dataType)
    .setStreamName("hydrationSource")
    .setType(DataSource.TYPE_RAW)
    .build();
}
 
Example #22
Source File: JSONEncoder.java    From react-native-google-fitness with MIT License 5 votes vote down vote up
private static WritableMap convertDataSource(DataSource ds) {
    WritableNativeMap map = new WritableNativeMap();
    map.putInt("type", ds.getType());
    map.putString("name", ds.getName());
    map.putString("appPackageName", ds.getAppPackageName());
    map.putString("streamIdentifier", ds.getStreamIdentifier());
    return map;
}
 
Example #23
Source File: Manager.java    From react-native-fitness with MIT License 4 votes vote down vote up
public void getSteps(Context context, double startDate, double endDate, String customInterval, final Promise promise){
    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();

    TimeUnit interval = getInterval(customInterval);

    DataReadRequest readRequest = new DataReadRequest.Builder()
            .aggregate(ESTIMATED_STEP_DELTAS,    DataType.AGGREGATE_STEP_COUNT_DELTA)
            .bucketByTime(1, interval)
            .setTimeRange((long) startDate, (long) endDate, TimeUnit.MILLISECONDS)
            .build();

    Fitness.getHistoryClient(context, GoogleSignIn.getLastSignedInAccount(context))
            .readData(readRequest)
            .addOnSuccessListener(new OnSuccessListener<DataReadResponse>() {
                @Override
                public void onSuccess(DataReadResponse dataReadResponse) {
                    if (dataReadResponse.getBuckets().size() > 0) {
                        WritableArray steps = Arguments.createArray();
                        for (Bucket bucket : dataReadResponse.getBuckets()) {
                            List<DataSet> dataSets = bucket.getDataSets();
                            for (DataSet dataSet : dataSets) {
                                processStep(dataSet, steps);
                            }
                        }
                        promise.resolve(steps);
                    }
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    promise.reject(e);
                }
            })
            .addOnCompleteListener(new OnCompleteListener<DataReadResponse>() {
                @Override
                public void onComplete(@NonNull Task<DataReadResponse> task) {
                }
            });
}
 
Example #24
Source File: GoogleFit.java    From OpenFit with MIT License 4 votes vote down vote up
private boolean insertProfileData () {
    boolean success = false;
    if(profileData != null) {
        Log.d(LOG_TAG, "write userData");

        DataSource heightDataSource = new DataSource.Builder()
        .setAppPackageName("com.solderbyte.openfit")
        .setDataType(DataType.TYPE_HEIGHT)
        .setName("Open Fit - profile data")
        .setType(DataSource.TYPE_RAW)
        .build();

        DataSource weightDataSource = new DataSource.Builder()
        .setAppPackageName("com.solderbyte.openfit")
        .setDataType(DataType.TYPE_WEIGHT)
        .setName("Open Fit - profile data")
        .setType(DataSource.TYPE_RAW)
        .build();

        Calendar cal = Calendar.getInstance();
        Date startDate = new Date(profileData.getTimeStamp());
        cal.setTime(startDate);
        cal.add(Calendar.SECOND, 1);
        Date endDate = new Date(cal.getTimeInMillis());

        DataSet dHeight = DataSet.create(heightDataSource);
        DataPoint pHeight = dHeight.createDataPoint().setTimeInterval(startDate.getTime(), endDate.getTime(), TimeUnit.MILLISECONDS);
        pHeight = pHeight.setFloatValues(profileData.getHeight() / 100);
        dHeight.add(pHeight);

        DataSet dWeight = DataSet.create(weightDataSource);
        DataPoint pWeight = dWeight.createDataPoint().setTimeInterval(startDate.getTime(), endDate.getTime(), TimeUnit.MILLISECONDS);
        pWeight = pWeight.setFloatValues(profileData.getWeight());
        dWeight.add(pWeight);

        com.google.android.gms.common.api.Status insertStatusH = Fitness.HistoryApi.insertData(mClient, dHeight).await(1, TimeUnit.MINUTES);
        com.google.android.gms.common.api.Status insertStatusW = Fitness.HistoryApi.insertData(mClient, dWeight).await(1, TimeUnit.MINUTES);

        if(!insertStatusH.isSuccess() || !insertStatusW.isSuccess()) {
            success = false;
            Log.d(LOG_TAG, "Profile data: There was a problem inserting the session");
        }
        else {
            success = true;
            Log.d(LOG_TAG, "Profile data inserted: " + insertStatusW);
        }

    }
    return success;
}