com.google.android.gms.fitness.request.DataReadRequest Java Examples

The following examples show how to use com.google.android.gms.fitness.request.DataReadRequest. 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: 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 #2
Source File: HydrationHistory.java    From react-native-google-fit with MIT License 6 votes vote down vote up
public ReadableArray getHistory(long startTime, long endTime) {
  DateFormat dateFormat = DateFormat.getDateInstance();

  DataReadRequest readRequest = new DataReadRequest.Builder()
    .read(this.dataType)
    .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS).build();

  DataReadResult dataReadResult = Fitness.HistoryApi.readData(googleFitManager.getGoogleApiClient(), readRequest)
    .await(1, TimeUnit.MINUTES);

  WritableArray map = Arguments.createArray();

  if (dataReadResult.getDataSets().size() > 0) {
    for (DataSet dataSet : dataReadResult.getDataSets()) {
      processDataSet(dataSet, map);
    }
  }

  return map;
}
 
Example #3
Source File: GoogleFit.java    From cordova-plugin-googlefit with MIT License 6 votes vote down vote up
/**
 * Return a {@link DataReadRequest} for all step count changes in the past week.
 */
private DataReadRequest queryDataWithBuckets(long startTime, long endTime, List<DataType> types, List<DataType> aggregations, int duration, TimeUnit time, int bucketType) {

    DataReadRequest.Builder builder = new DataReadRequest.Builder();

    for (int i=0; i< types.size(); i++) {
        builder.aggregate(types.get(i), aggregations.get(i));
    }

    switch (bucketType) {
        case 2:
            builder.bucketByActivitySegment(duration, time);
            break;
        case 1:
            builder.bucketByActivityType(duration, time);
            break;
        case 0:
        default:
            builder.bucketByTime(duration, time);
            break;
    }

    return builder.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS).build();
}
 
Example #4
Source File: GoogleFit.java    From cordova-plugin-googlefit with MIT License 6 votes vote down vote up
/**
 * Return a {@link DataReadRequest} for all step count changes in the past week.
 */
private DataReadRequest queryDataWithBuckets(long startTime, long endTime, List<DataType> types, List<DataType> aggregations, int duration, TimeUnit time, int bucketType) {

    DataReadRequest.Builder builder = new DataReadRequest.Builder();

    for (int i=0; i< types.size(); i++) {
        builder.aggregate(types.get(i), aggregations.get(i));
    }

    switch (bucketType) {
        case 2:
            builder.bucketByActivitySegment(duration, time);
            break;
        case 1:
            builder.bucketByActivityType(duration, time);
            break;
        case 0:
        default:
            builder.bucketByTime(duration, time);
            break;
    }

    return builder.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS).build();
}
 
Example #5
Source File: StepsHelper.java    From drip-steps with Apache License 2.0 6 votes vote down vote up
/**
 * Query to get the num of steps since 00:00 until now
 */
private DataReadRequest queryFitnessData() {
	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, 0);
	cal.set(Calendar.SECOND, 0);
	cal.set(Calendar.MILLISECOND, 0);
	long startTime = cal.getTimeInMillis();

	return new DataReadRequest.Builder()
			.aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
			.bucketByTime(1, TimeUnit.DAYS)
			.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
			.build();
}
 
Example #6
Source File: Manager.java    From react-native-fitness with MIT License 5 votes vote down vote up
public void getDistance(Context context, double startDate, double endDate, String customInterval, final Promise promise) {
    TimeUnit interval = getInterval(customInterval);

    DataReadRequest readRequest = new DataReadRequest.Builder()
            .aggregate(DataType.TYPE_DISTANCE_DELTA, DataType.AGGREGATE_DISTANCE_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 distances = Arguments.createArray();
                        for (Bucket bucket : dataReadResponse.getBuckets()) {
                            List<DataSet> dataSets = bucket.getDataSets();
                            for (DataSet dataSet : dataSets) {
                                processDistance(dataSet, distances);
                            }
                        }
                        promise.resolve(distances);
                    }
                }
            })
            .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 #7
Source File: DataQueries.java    From GoogleFitExample with Apache License 2.0 5 votes vote down vote up
/**
 * GET step count for a specific ACTIVITY.
 *
 * Retrieves a raw step count.
 *
 */
public static DataReadRequest queryStepCount(long startTime, long endTime) {
    return new DataReadRequest.Builder()
            .aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
            .bucketByTime(1, TimeUnit.DAYS)
            .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
            .enableServerQueries() // Used to retrieve data from cloud
            .build();
}
 
Example #8
Source File: DataQueries.java    From GoogleFitExample with Apache License 2.0 5 votes vote down vote up
public static DataReadRequest queryActivitySegmentBucket(long startTime, long endTime) {
    return new DataReadRequest.Builder()
            .aggregate(DataType.TYPE_ACTIVITY_SEGMENT, DataType.AGGREGATE_ACTIVITY_SUMMARY)
            .bucketByTime(1, TimeUnit.DAYS)
            .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
            .enableServerQueries() // Used to retrieve data from cloud
            .build();
}
 
Example #9
Source File: DataQueries.java    From GoogleFitExample with Apache License 2.0 5 votes vote down vote up
/**
 * GET data by ACTIVITY
 *
 * The Google Fit API suggests that we don't want granular data, HOWEVER, we need granular
 * data to do anything remotely interesting with the data. This takes a while so we'll store
 * the results in a local db.
 *
 * After retrieving all activity segments, we go back and ask for step counts for each
 * segment. This allows us to summarize steps and duration per activity.
 *
 */
public static DataReadRequest queryActivitySegment(long startTime, long endTime, boolean isNetworkConnected) {
    if(isNetworkConnected) {
        return new DataReadRequest.Builder()
                .read(DataType.TYPE_ACTIVITY_SEGMENT)
                .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
                .enableServerQueries() // Used to retrieve data from cloud.
                .build();
    }else {
        return new DataReadRequest.Builder()
                .read(DataType.TYPE_ACTIVITY_SEGMENT)
                .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
                .build();
    }
}
 
Example #10
Source File: StepsHelper.java    From drip-steps with Apache License 2.0 5 votes vote down vote up
public void fetchStepsCount() {
	ex.execute(new Runnable() {
		@Override
		public void run() {
			// Find steps from Fitness API
			DataReadRequest r = queryFitnessData();
			DataReadResult dataReadResult = Fitness.HistoryApi.readData(client, r).await(1, TimeUnit.MINUTES);
			boolean stepsFetched = false;
			if (dataReadResult.getBuckets().size() > 0) {
				Bucket bucket = dataReadResult.getBuckets().get(0);
				DataSet ds = bucket.getDataSet(DataType.TYPE_STEP_COUNT_DELTA);
				if (ds != null) {
					for (DataPoint dp : ds.getDataPoints()) {
						for (Field field : dp.getDataType().getFields()) {
							if (field.getName().equals("steps")) {
								stepsFetched = true;
								listener.onStepsCountFetched(dp.getValue(field).asInt());
							}
						}
					}
				}
			}

			if (!stepsFetched) {
				// No steps today yet or no fitness data available
				listener.onStepsCountFetched(0);
			}
		}
	});
}
 
Example #11
Source File: CalorieHistory.java    From react-native-google-fit with MIT License 5 votes vote down vote up
private float getBasalAVG(long _et) throws Exception {
    float basalAVG = 0;
    Calendar cal = java.util.Calendar.getInstance();
    cal.setTime(new Date(_et));
    //set start time to a week before end time
    cal.add(Calendar.WEEK_OF_YEAR, -1);
    long nst = cal.getTimeInMillis();

    DataReadRequest.Builder builder = new DataReadRequest.Builder();
    builder.aggregate(DataType.TYPE_BASAL_METABOLIC_RATE, DataType.AGGREGATE_BASAL_METABOLIC_RATE_SUMMARY);
    builder.bucketByTime(1, TimeUnit.DAYS);
    builder.setTimeRange(nst, _et, TimeUnit.MILLISECONDS);
    DataReadRequest readRequest = builder.build();

    DataReadResult dataReadResult = Fitness.HistoryApi.readData(googleFitManager.getGoogleApiClient(), readRequest).await();

    if (dataReadResult.getStatus().isSuccess()) {
        JSONObject obj = new JSONObject();
        int avgsN = 0;
        for (Bucket bucket : dataReadResult.getBuckets()) {
            // in the com.google.bmr.summary data type, each data point represents
            // the average, maximum and minimum basal metabolic rate, in kcal per day, over the time interval of the data point.
            DataSet ds = bucket.getDataSet(DataType.AGGREGATE_BASAL_METABOLIC_RATE_SUMMARY);
            for (DataPoint dp : ds.getDataPoints()) {
                float avg = dp.getValue(Field.FIELD_AVERAGE).asFloat();
                basalAVG += avg;
                avgsN++;
            }
        }
        // do the average of the averages
        if (avgsN != 0) basalAVG /= avgsN; // this a daily average
        return basalAVG;
    } else throw new Exception(dataReadResult.getStatus().getStatusMessage());
}
 
Example #12
Source File: StepHistory.java    From react-native-google-fit with MIT License 5 votes vote down vote up
public void getUserInputSteps(long startTime, long endTime, final Callback successCallback) {

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
        dateFormat.setTimeZone(TimeZone.getDefault());

        Log.i(TAG, "Range Start: " + dateFormat.format(startTime));
        Log.i(TAG, "Range End: " + dateFormat.format(endTime));

        final DataReadRequest readRequest = new DataReadRequest.Builder()
            .read(DataType.TYPE_STEP_COUNT_DELTA)
            .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
            .build();

        DataReadResult dataReadResult =
            Fitness.HistoryApi.readData(googleFitManager.getGoogleApiClient(), readRequest).await(1, TimeUnit.MINUTES);

        DataSet stepData = dataReadResult.getDataSet(DataType.TYPE_STEP_COUNT_DELTA);
    
        int userInputSteps = 0;

        for (DataPoint dp : stepData.getDataPoints()) {
            for(Field field : dp.getDataType().getFields()) {
                if("user_input".equals(dp.getOriginalDataSource().getStreamName())){
                    int steps = dp.getValue(field).asInt();
                    userInputSteps += steps;
                }
            }
        }
      
        successCallback.invoke(userInputSteps);
    }
 
Example #13
Source File: GoogleFitModule.java    From react-native-google-fitness with MIT License 5 votes vote down vote up
@ReactMethod
public void history_readData(String jsonStatement, final Promise promise) {
    try {
        DataReadRequest dataReadRequest = (DataReadRequest) StatementFactory
                .fromJson(jsonStatement)
                .execute(new JavaContext(), null);

        getHistoryClient()
                .readData(dataReadRequest)
                .addOnFailureListener(new SimpleFailureListener(promise))
                .addOnSuccessListener(new OnSuccessListener<DataReadResponse>() {
                    @Override
                    public void onSuccess(DataReadResponse result) {
                        WritableNativeArray dataSets = JSONEncoder.convertDataSets(result.getDataSets());
                        WritableNativeArray buckets = JSONEncoder.convertBuckets(result.getBuckets());

                        WritableNativeMap map = new WritableNativeMap();
                        map.putString("status", result.getStatus().toString());
                        map.putArray("dataSets", dataSets);
                        map.putArray("buckets", buckets);
                        promise.resolve(map);
                    }
                });
    } catch (Exception e) {
        Log.e(TAG, "Error in history_readData()", e);
        promise.reject(e);
    }
}
 
Example #14
Source File: Manager.java    From react-native-fitness with MIT License 5 votes vote down vote up
public void getHeartRate(Context context, double startDate, double endDate, String customInterval,final Promise promise) {
    TimeUnit interval = getInterval(customInterval);

    DataReadRequest readRequest = new DataReadRequest.Builder()
            .aggregate(DataType.TYPE_HEART_RATE_BPM, DataType.AGGREGATE_HEART_RATE_SUMMARY)
            .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 heartRates = Arguments.createArray();
                        for (Bucket bucket : dataReadResponse.getBuckets()) {
                            List<DataSet> dataSets = bucket.getDataSets();
                            for (DataSet dataSet : dataSets) {
                                processHeartRate(dataSet, heartRates);
                            }
                        }
                        promise.resolve(heartRates);
                    }
                }
            })
            .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 #15
Source File: Manager.java    From react-native-fitness with MIT License 5 votes vote down vote up
public void getCalories(Context context, double startDate, double endDate, String customInterval, final Promise promise) {
    TimeUnit interval = getInterval(customInterval);

    DataReadRequest readRequest = new DataReadRequest.Builder()
            .aggregate(DataType.TYPE_CALORIES_EXPENDED, DataType.AGGREGATE_CALORIES_EXPENDED)
            .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 calories = Arguments.createArray();
                        for (Bucket bucket : dataReadResponse.getBuckets()) {
                            List<DataSet> dataSets = bucket.getDataSets();
                            for (DataSet dataSet : dataSets) {
                                processDistance(dataSet, calories);
                            }
                        }
                        promise.resolve(calories);
                    }
                }
            })
            .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 #16
Source File: ActivityHistory.java    From react-native-google-fit with MIT License 4 votes vote down vote up
public ReadableArray getActivitySamples(long startTime, long endTime) {
    WritableArray results = Arguments.createArray();
    DataReadRequest readRequest = new DataReadRequest.Builder()
            .aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
            .aggregate(DataType.TYPE_CALORIES_EXPENDED, DataType.AGGREGATE_CALORIES_EXPENDED)
            .aggregate(DataType.TYPE_DISTANCE_DELTA, DataType.AGGREGATE_DISTANCE_DELTA)
            .bucketByActivitySegment(1, TimeUnit.SECONDS)
            .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
            .build();

    DataReadResult dataReadResult = Fitness.HistoryApi.readData(googleFitManager.getGoogleApiClient(), readRequest).await(1, TimeUnit.MINUTES);

    List<Bucket> buckets = dataReadResult.getBuckets();
    for (Bucket bucket : buckets) {
        String activityName = bucket.getActivity();
        int activityType = bucket.getBucketType();
        if (!bucket.getDataSets().isEmpty()) {
            long start = bucket.getStartTime(TimeUnit.MILLISECONDS);
            long end = bucket.getEndTime(TimeUnit.MILLISECONDS);
            Date startDate = new Date(start);
            Date endDate = new Date(end);
            WritableMap map = Arguments.createMap();
            map.putDouble("start",start);
            map.putDouble("end",end);
            map.putString("activityName", activityName);
            String deviceName = "";
            String sourceId = "";
            boolean isTracked = true;
            for (DataSet dataSet : bucket.getDataSets()) {
                for (DataPoint dataPoint : dataSet.getDataPoints()) {
                    try {
                        int deviceType = dataPoint.getOriginalDataSource().getDevice().getType();
                        if (deviceType == TYPE_WATCH) {
                            deviceName = "Android Wear";
                        } else {
                            deviceName = "Android";
                        }
                    } catch (Exception e) {
                    }
                    sourceId = dataPoint.getOriginalDataSource().getAppPackageName();
                    if (startDate.getTime() % 1000 == 0 && endDate.getTime() % 1000 == 0) {
                        isTracked = false;
                    }
                    for (Field field : dataPoint.getDataType().getFields()) {
                        String fieldName = field.getName();
                        switch (fieldName) {
                            case STEPS_FIELD_NAME:
                                map.putInt("quantity", dataPoint.getValue(field).asInt());
                                break;
                            case DISTANCE_FIELD_NAME:
                                map.putDouble(fieldName, dataPoint.getValue(field).asFloat());
                                break;
                            case CALORIES_FIELD_NAME:
                                map.putDouble(fieldName, dataPoint.getValue(field).asFloat());
                            default:
                                Log.w(TAG, "don't specified and handled: " + fieldName);
                        }
                    }
                }
            }
            map.putString("device", deviceName);
            map.putString("sourceName", deviceName);
            map.putString("sourceId", sourceId);
            map.putBoolean("tracked", isTracked);
            results.pushMap(map);
        }
    }
    
    return results;
}
 
Example #17
Source File: GoogleFit.java    From cordova-plugin-googlefit with MIT License 4 votes vote down vote up
public GetStuff(DataReadRequest request, final CallbackContext callbackContext) {
    this.request = request;
    this.callbackContext = callbackContext;
}
 
Example #18
Source File: GoogleFit.java    From cordova-plugin-googlefit with MIT License 4 votes vote down vote up
public GetStuff(DataReadRequest request, final CallbackContext callbackContext) {
    this.request = request;
    this.callbackContext = callbackContext;
}
 
Example #19
Source File: DataManager.java    From GoogleFitExample with Apache License 2.0 4 votes vote down vote up
/**
 * Walk through all activity fields in a segment dataset and writes them to the cache. Used to
 * store data to display in reports and graphs.
 *
 * @param dataSet set of data from the Google Fit API
 */
private boolean writeDataSetToCache(DataSet dataSet) {
    boolean wroteDataToCache = true;
    SQLiteDatabase db = getDatabase();
    for (DataPoint dp : dataSet.getDataPoints()) {
        // Populate db cache with data
        for(Field field : dp.getDataType().getFields()) {
            if(field.getName().equals("activity") && dp.getDataType().getName().equals("com.google.activity.segment")) {
                //Log.i(TAG, dp.getOriginalDataSource().getAppPackageName());
                dp.getVersionCode();
                long startTime = dp.getStartTime(TimeUnit.MILLISECONDS);
                int activity = dp.getValue(field).asInt();
                Log.i(TAG, "Found: " + WorkoutTypes.getActivityTextById(activity) + " entered by: " + dp.getOriginalDataSource().getAppPackageName());
                Workout workout;

                if (db != null && db.isOpen()) {
                    workout = cupboard().withDatabase(db).get(Workout.class, startTime);
                } else {
                    Log.w(TAG, "Warning: db is null");
                    return false;
                }


                // When the workout is null, we need to cache it. If the background task has completed,
                // then we have at most 8 - 12 hours of data. Recent data is likely to change so over-
                // write it.
                Context context = getApplicationContext();
                if (context != null && isConnected()) {
                    //if (workout == null || UserPreferences.getBackgroundLoadComplete(context)) {
                    long endTime = dp.getEndTime(TimeUnit.MILLISECONDS);
                    DataReadRequest readRequest = DataQueries.queryStepCount(startTime, endTime);
                    DataReadResult dataReadResult = Fitness.HistoryApi.readData(mClient, readRequest).await(2, TimeUnit.MINUTES);
                    int stepCount = countStepData(dataReadResult);
                    workout = new Workout();
                    workout._id = startTime;
                    workout.start = startTime;
                    workout.duration = endTime - startTime;
                    workout.stepCount = stepCount;
                    workout.type = activity;
                    workout.packageName = dp.getOriginalDataSource().getAppPackageName();
                    //Log.v("MainActivity", "Put Cache: " + WorkoutTypes.getWorkOutTextById(workout.type) + " " + workout.duration);
                    if (db != null && db.isOpen()) {
                        if (workout.duration > 0) {
                            Log.i(TAG, "Wrote to DB: " + workout.toString());
                            cupboard().withDatabase(db).put(workout);
                        } else {
                            Log.w(TAG, "Warning: duration is 0");
                        }

                        //wroteDataToCache = true;
                    } else {
                        wroteDataToCache = false;
                    }
                    //} else {
                        // Do not overwrite data if the initial load is in progress. This would take too
                        // long and prevent us from accumulating a base set of data.
                    //}
                } else {
                    wroteDataToCache = false;
                }

            }
        }
    }
    return wroteDataToCache;
}
 
Example #20
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 #21
Source File: GoogleFit.java    From cordova-plugin-googlefit with MIT License 3 votes vote down vote up
/**
 * Return a {@link DataReadRequest} for all step count changes in the past week.
 */
private DataReadRequest queryData(long startTime, long endTime, List<DataType> types) {


    DataReadRequest.Builder builder = new DataReadRequest.Builder();

    for (DataType dt : types) {
        builder.read(dt);
    }

    return builder.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS).build();
}
 
Example #22
Source File: GoogleFit.java    From cordova-plugin-googlefit with MIT License 3 votes vote down vote up
/**
 * Return a {@link DataReadRequest} for all step count changes in the past week.
 */
private DataReadRequest queryData(long startTime, long endTime, List<DataType> types) {


    DataReadRequest.Builder builder = new DataReadRequest.Builder();

    for (DataType dt : types) {
        builder.read(dt);
    }

    return builder.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS).build();
}