com.google.android.gms.fitness.result.DataReadResult Java Examples

The following examples show how to use com.google.android.gms.fitness.result.DataReadResult. 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 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 #2
Source File: GoogleFit.java    From cordova-plugin-googlefit with MIT License 6 votes vote down vote up
@Override
public void run() {
    if (!mClient.isConnected()) {
        mClient.connect();
    }

    Fitness.HistoryApi.readData(mClient, request)
        .setResultCallback(new ResultCallback<DataReadResult>() {
            @Override
            public void onResult(DataReadResult dataReadResult) {

                if (dataReadResult.getBuckets().size() > 0) {
                    callbackContext.success(convertBucketsToJson(dataReadResult.getBuckets())); // Thread-safe.
                } else if (dataReadResult.getDataSets().size() > 0) {
                    callbackContext.success(convertDatasetsToJson(dataReadResult.getDataSets())); // Thread-safe.
                } else {
                    callbackContext.error("No dataset and no buckets."); // Thread-safe.
                }
            }
        });
}
 
Example #3
Source File: GoogleFit.java    From cordova-plugin-googlefit with MIT License 6 votes vote down vote up
@Override
public void run() {
    if (!mClient.isConnected()) {
        mClient.connect();
    }

    Fitness.HistoryApi.readData(mClient, request)
        .setResultCallback(new ResultCallback<DataReadResult>() {
            @Override
            public void onResult(DataReadResult dataReadResult) {

                if (dataReadResult.getBuckets().size() > 0) {
                    callbackContext.success(convertBucketsToJson(dataReadResult.getBuckets())); // Thread-safe.
                } else if (dataReadResult.getDataSets().size() > 0) {
                    callbackContext.success(convertDatasetsToJson(dataReadResult.getDataSets())); // Thread-safe.
                } else {
                    callbackContext.error("No dataset and no buckets."); // Thread-safe.
                }
            }
        });
}
 
Example #4
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 #5
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 #6
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 #7
Source File: DataManager.java    From GoogleFitExample with Apache License 2.0 5 votes vote down vote up
private boolean writeActivityDataToCache(DataReadResult dataReadResult) {
    boolean wroteDataToCache = false;
    for (DataSet dataSet : dataReadResult.getDataSets()) {
        wroteDataToCache = wroteDataToCache || writeDataSetToCache(dataSet);
    }
    return wroteDataToCache;
}
 
Example #8
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 #9
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;
}