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

The following examples show how to use com.google.android.gms.fitness.data.Field. 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: Mission.java    From android-play-games-in-motion with Apache License 2.0 7 votes vote down vote up
@Override
public void onDataPoint(DataPoint dataPoint) {
    // If we get data before the mission has started, discard them.
    if (!mIsStarted) {
        return;
    }
    DataType dataType = dataPoint.getDataType();
    for (Field field : dataType.getFields()) {
        Value val = dataPoint.getValue(field);
        if (dataType.equals(DataType.TYPE_STEP_COUNT_DELTA)) {
            onStepTaken(val.asInt());
        } else if (dataType.equals(DataType.TYPE_SPEED)) {
            // Data comes in as meters per second, have to convert to minutes per mile.
            float speedMetersPerSeconds = val.asFloat();
            updateChallengePace(Utils.metersPerSecondToMinutesPerMile(speedMetersPerSeconds));
        }
    }
}
 
Example #2
Source File: GoogleFitSessionManagerTest.java    From JayPS-AndroidApp with MIT License 6 votes vote down vote up
@SmallTest
public void test2UniqueActivityEventsCreates2DataPoints() {
    startSession(1000);

    _sessionManager.addDataPoint(2000, DetectedActivity.RUNNING);
    _sessionManager.addDataPoint(3000, DetectedActivity.WALKING);

    _sessionManager.saveActiveSession(4000);

    DataSet dataSet = getDataSet();

    assertEquals(2,dataSet.getDataPoints().size());

    assertEquals("Start time should equal data start time",2000,dataSet.getDataPoints().get(0).getStartTime(TimeUnit.MILLISECONDS));
    assertEquals("End time should equal session end time", 3000,dataSet.getDataPoints().get(0).getEndTime(TimeUnit.MILLISECONDS));
    assertEquals("Activity should equal unknown", FitnessActivities.RUNNING, dataSet.getDataPoints().get(0).getValue(Field.FIELD_ACTIVITY).asActivity());

    assertEquals("Start time should equal data start time",3000,dataSet.getDataPoints().get(1).getStartTime(TimeUnit.MILLISECONDS));
    assertEquals("End time should equal session end time", 4000,dataSet.getDataPoints().get(1).getEndTime(TimeUnit.MILLISECONDS));
    assertEquals("Activity should equal unknown", FitnessActivities.WALKING, dataSet.getDataPoints().get(1).getValue(Field.FIELD_ACTIVITY).asActivity());
}
 
Example #3
Source File: GoogleFitSessionManagerTest.java    From JayPS-AndroidApp with MIT License 6 votes vote down vote up
@SmallTest
public void test2DuplicateActivityEventsCreates1DataPoints() {
    startSession(1000);

    _sessionManager.addDataPoint(2000, DetectedActivity.RUNNING);
    _sessionManager.addDataPoint(3000, DetectedActivity.RUNNING);

    _sessionManager.saveActiveSession(4000);

    DataSet dataSet = getDataSet();

    assertEquals(1,dataSet.getDataPoints().size());
    assertEquals("Start time should equal data start time",2000,dataSet.getDataPoints().get(0).getStartTime(TimeUnit.MILLISECONDS));
    assertEquals("End time should equal session end time", 4000,dataSet.getDataPoints().get(0).getEndTime(TimeUnit.MILLISECONDS));
    assertEquals("Activity should equal unknown", FitnessActivities.RUNNING, dataSet.getDataPoints().get(0).getValue(Field.FIELD_ACTIVITY).asActivity());
}
 
Example #4
Source File: StepCounter.java    From react-native-google-fit with MIT License 6 votes vote down vote up
@Override
public void onDataPoint(DataPoint dataPoint) {
    DataType type = dataPoint.getDataType();
    Log.i(TAG, "Detected DataPoint type: " + type);

    for (final Field field : type.getFields()) {
        final Value value = dataPoint.getValue(field);
        Log.i(TAG, "Detected DataPoint field: " + field.getName());
        Log.i(TAG, "Detected DataPoint value: " + value);


   /*     activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mReactContext.getApplicationContext(), "Field: " + field.getName() + " Value: " + value, Toast.LENGTH_SHORT).show();
            }
        });*/

        if(type.equals(DataType.TYPE_STEP_COUNT_DELTA)) {
            WritableMap map = Arguments.createMap();
            map.putDouble("steps", value.asInt());
            sendEvent(this.mReactContext, "StepChangedEvent", map);
        }

    }
}
 
Example #5
Source File: JSONEncoder.java    From react-native-google-fitness with MIT License 6 votes vote down vote up
public static WritableNativeArray convertDataSet(DataSet dataSet) {
    WritableNativeArray jsonDataSet = new WritableNativeArray();
    for (DataPoint dp : dataSet.getDataPoints()) {
        WritableNativeMap jsonDataPoint = new WritableNativeMap();

        jsonDataPoint.putString("type", dp.getDataType().getName());
        jsonDataPoint.putString("source", dp.getOriginalDataSource().getAppPackageName());
        jsonDataPoint.putString("start", dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
        jsonDataPoint.putString("end", dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)));

        WritableNativeArray jsonFieldValuePairs = new WritableNativeArray();
        for (Field field : dp.getDataType().getFields()) {
            WritableNativeMap jsonFieldValuePair = new WritableNativeMap();
            jsonFieldValuePair.putString("field", field.getName());
            jsonFieldValuePair.putString("value", dp.getValue(field).toString());
            jsonFieldValuePairs.pushMap(jsonFieldValuePair);
        }
        jsonDataPoint.putArray("fields", jsonFieldValuePairs);

        jsonDataSet.pushMap(jsonDataPoint);
    }
    return jsonDataSet;
}
 
Example #6
Source File: GoogleFitSessionManagerTest.java    From JayPS-AndroidApp with MIT License 6 votes vote down vote up
@SmallTest
public void testSaveActiveSessionCallBackWithNoRecognisedActivityCreates1DataPoints() {

    // setup the mock to return the same start time as set
    startSession(1000);

    when(_mockSession.getStartTime(TimeUnit.MILLISECONDS)).thenReturn((long)1000);

    _sessionManager.saveActiveSession(2000);
    DataSet dataSet = getDataSet();

    assertEquals(1,dataSet.getDataPoints().size());
    assertEquals("Start time should equal session start time",1000,dataSet.getDataPoints().get(0).getStartTime(TimeUnit.MILLISECONDS));
    assertEquals("End time should equal session end time", 2000,dataSet.getDataPoints().get(0).getEndTime(TimeUnit.MILLISECONDS));
    assertEquals("Activity should equal unknown", FitnessActivities.UNKNOWN, dataSet.getDataPoints().get(0).getValue(Field.FIELD_ACTIVITY).asActivity());
}
 
Example #7
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 #8
Source File: NutritionHistory.java    From react-native-google-fit with MIT License 6 votes vote down vote up
private void processDataSet(DataSet dataSet, WritableArray map) {
    Log.i(TAG, "Data returned for Data type: " + dataSet.getDataType().getName());
    DateFormat dateFormat = DateFormat.getDateInstance();
    DateFormat timeFormat = DateFormat.getTimeInstance();

    for (DataPoint dp : dataSet.getDataPoints()) {
        Log.i(TAG, "Data point:");
        Log.i(TAG, "\tType: " + dp.getDataType().getName());
        Log.i(TAG, "\tStart: " + dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)) + " "
                + timeFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
        Log.i(TAG, "\tEnd: " + dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)) + " "
                + timeFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));

        WritableMap nutritionMap = Arguments.createMap();
        Value nutrients = dp.getValue((Field.FIELD_NUTRIENTS));

        nutritionMap.putDouble("date", dp.getStartTime(TimeUnit.MILLISECONDS));
        nutritionMap.putMap("nutrients", getNutrientsAsMap(nutrients));

        map.pushMap(nutritionMap);
    }
}
 
Example #9
Source File: StepHistory.java    From react-native-google-fit with MIT License 6 votes vote down vote up
private void processDataSet(DataSet dataSet, WritableArray map) {
    //Log.i(TAG, "Data returned for Data type: " + dataSet.getDataType().getName());

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

    WritableMap stepMap = Arguments.createMap();

    for (DataPoint dp : dataSet.getDataPoints()) {
        Log.i(TAG, "\tData point:");
        Log.i(TAG, "\t\tType : " + dp.getDataType().getName());
        Log.i(TAG, "\t\tStart: " + dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
        Log.i(TAG, "\t\tEnd  : " + dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)));

        for(Field field : dp.getDataType().getFields()) {
            Log.i(TAG, "\t\tField: " + field.getName() +
                    " Value: " + dp.getValue(field));

            stepMap.putDouble("startDate", dp.getStartTime(TimeUnit.MILLISECONDS));
            stepMap.putDouble("endDate", dp.getEndTime(TimeUnit.MILLISECONDS));
            stepMap.putDouble("steps", dp.getValue(field).asInt());
            map.pushMap(stepMap);
        }
    }
}
 
Example #10
Source File: DataManager.java    From GoogleFitExample with Apache License 2.0 6 votes vote down vote up
/**
 * Walk through all fields in a step_count dataset and return the sum of steps. Used to
 * calculate step counts.
 *
 * @param dataSet set of data from the Google Fit API
 */
private int parseDataSet(DataSet dataSet) {
    int dataSteps = 0;
    for (DataPoint dp : dataSet.getDataPoints()) {
        // Accumulate step count for estimate

        if(dp.getDataType().getName().equals("com.google.step_count.delta")) {

            for (Field field : dp.getDataType().getFields()) {
                if (dp.getValue(field).asInt() > 0) {
                    dataSteps += dp.getValue(field).asInt();
                }
            }
        }
    }
    return dataSteps;
}
 
Example #11
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
private void showDataSet(DataSet dataSet) {
    Log.e("History", "Data returned for Data type: " + dataSet.getDataType().getName());
    DateFormat dateFormat = DateFormat.getDateInstance();
    DateFormat timeFormat = DateFormat.getTimeInstance();

    for (DataPoint dp : dataSet.getDataPoints()) {
        Log.e("History", "Data point:");
        Log.e("History", "\tType: " + dp.getDataType().getName());
        Log.e("History", "\tStart: " + dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)) + " " + timeFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
        Log.e("History", "\tEnd: " + dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)) + " " + timeFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
        for(Field field : dp.getDataType().getFields()) {
            Log.e("History", "\tField: " + field.getName() +
                    " Value: " + dp.getValue(field));
        }
    }
}
 
Example #12
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 #13
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 #14
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 #15
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 #16
Source File: GoogleFit.java    From OpenFit with MIT License 5 votes vote down vote up
public void parseDataSet(DataSet dataSet) {
    for(DataPoint dp : dataSet.getDataPoints()) {
        Date start = new Date(dp.getStartTime(TimeUnit.MILLISECONDS));
        Date end = new Date(dp.getEndTime(TimeUnit.MILLISECONDS));
        Log.d(LOG_TAG, "Type: " + dp.getDataType().getName());
        Log.d(LOG_TAG, "Date: " + start + ":" + end);
        for(Field field : dp.getDataType().getFields()) {
            Log.d(LOG_TAG, "Field: " + field.getName() + " Value: " + dp.getValue(field));
        }
    }
}
 
Example #17
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
@Override
public void onDataPoint(DataPoint dataPoint) {
    for( final Field field : dataPoint.getDataType().getFields() ) {
        final Value value = dataPoint.getValue( field );
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), "Field: " + field.getName() + " Value: " + value, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
 
Example #18
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
private void initCallbacks() {
    mSubscribeResultCallback = new ResultCallback<Status>() {
        @Override
        public void onResult(@NonNull Status status) {
            if (status.isSuccess()) {
                if (status.getStatusCode() == FitnessStatusCodes.SUCCESS_ALREADY_SUBSCRIBED) {
                    Log.e( "RecordingAPI", "Already subscribed to the Recording API");
                } else {
                    Log.e("RecordingAPI", "Subscribed to the Recording API");
                }
            }
        }
    };

    mCancelSubscriptionResultCallback = new ResultCallback<Status>() {
        @Override
        public void onResult(@NonNull Status status) {
            if (status.isSuccess()) {
                Log.e( "RecordingAPI", "Canceled subscriptions!");
            } else {
                // Subscription not removed
                Log.e("RecordingAPI", "Failed to cancel subscriptions");
            }
        }
    };

    mListSubscriptionsResultCallback = new ResultCallback<ListSubscriptionsResult>() {
        @Override
        public void onResult(@NonNull ListSubscriptionsResult listSubscriptionsResult) {
            for (Subscription subscription : listSubscriptionsResult.getSubscriptions()) {
                DataType dataType = subscription.getDataType();
                Log.e( "RecordingAPI", dataType.getName() );
                for (Field field : dataType.getFields() ) {
                    Log.e( "RecordingAPI", field.toString() );
                }
            }
        }
    };
}
 
Example #19
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 #20
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 #21
Source File: GoogleFitSessionManagerTest.java    From JayPS-AndroidApp with MIT License 5 votes vote down vote up
@SmallTest
public void testNewWALKINGActivityEventCreates1DataPoints() {
    startSession(1000);

    _sessionManager.addDataPoint(2000, DetectedActivity.WALKING);

    _sessionManager.saveActiveSession(3000);

    DataSet dataSet = getDataSet();

    assertEquals(1,dataSet.getDataPoints().size());
    assertEquals("Start time should equal data start time",2000,dataSet.getDataPoints().get(0).getStartTime(TimeUnit.MILLISECONDS));
    assertEquals("End time should equal session end time", 3000,dataSet.getDataPoints().get(0).getEndTime(TimeUnit.MILLISECONDS));
    assertEquals("Activity should equal unknown", FitnessActivities.WALKING, dataSet.getDataPoints().get(0).getValue(Field.FIELD_ACTIVITY).asActivity());
}
 
Example #22
Source File: GoogleFitSessionManagerTest.java    From JayPS-AndroidApp with MIT License 5 votes vote down vote up
@SmallTest
public void testNewON_BICYCLEActivityEventCreates1DataPoints() {
    startSession(1000);

    _sessionManager.addDataPoint(2000, DetectedActivity.ON_BICYCLE);

    _sessionManager.saveActiveSession(3000);

    DataSet dataSet = getDataSet();

    assertEquals(1,dataSet.getDataPoints().size());
    assertEquals("Start time should equal data start time",2000,dataSet.getDataPoints().get(0).getStartTime(TimeUnit.MILLISECONDS));
    assertEquals("End time should equal session end time", 3000,dataSet.getDataPoints().get(0).getEndTime(TimeUnit.MILLISECONDS));
    assertEquals("Activity should equal unknown", FitnessActivities.BIKING, dataSet.getDataPoints().get(0).getValue(Field.FIELD_ACTIVITY).asActivity());
}
 
Example #23
Source File: GoogleFitSessionManagerTest.java    From JayPS-AndroidApp with MIT License 5 votes vote down vote up
@SmallTest
public void testNewRUNNINGActivityEventCreates1DataPoints() {
    startSession(1000);

    _sessionManager.addDataPoint(2000, DetectedActivity.RUNNING);

    _sessionManager.saveActiveSession(3000);

    DataSet dataSet = getDataSet();

    assertEquals(1,dataSet.getDataPoints().size());
    assertEquals("Start time should equal data start time",2000,dataSet.getDataPoints().get(0).getStartTime(TimeUnit.MILLISECONDS));
    assertEquals("End time should equal session end time", 3000,dataSet.getDataPoints().get(0).getEndTime(TimeUnit.MILLISECONDS));
    assertEquals("Activity should equal unknown", FitnessActivities.RUNNING, dataSet.getDataPoints().get(0).getValue(Field.FIELD_ACTIVITY).asActivity());
}
 
Example #24
Source File: BodyHistory.java    From react-native-google-fit with MIT License 5 votes vote down vote up
private void processDataSet(DataSet dataSet, WritableArray map) {
    //Log.i(TAG, "Data returned for Data type: " + dataSet.getDataType().getName());
    Format formatter = new SimpleDateFormat("EEE");

    WritableMap bodyMap = Arguments.createMap();

    for (DataPoint dp : dataSet.getDataPoints()) {
        String day = formatter.format(new Date(dp.getStartTime(TimeUnit.MILLISECONDS)));

        bodyMap.putString("day", day);
        bodyMap.putDouble("startDate", dp.getStartTime(TimeUnit.MILLISECONDS));
        bodyMap.putDouble("endDate", dp.getEndTime(TimeUnit.MILLISECONDS));
        bodyMap.putString("addedBy", dp.getOriginalDataSource().getAppPackageName());

        // When there is a short interval between weight readings (< 1 hour or so), some phones e.g.
        // Galaxy S5 use the average of the readings, whereas other phones e.g. Huawei P9 Lite use the
        // most recent of the bunch (this might be related to Android versions - 6.0.1 vs 7.0 in this
        // example for former and latter)
        //
        // For aggregated weight summary, only the min, max and average values are available (i.e. the
        // most recent sample is not an option), so use average value to maximise the match between values
        // returned here and values as reported by Google Fit app
        if (this.dataType == DataType.TYPE_WEIGHT) {
            bodyMap.putDouble("value", dp.getValue(Field.FIELD_AVERAGE).asFloat());
        } else {
            bodyMap.putDouble("value", dp.getValue(Field.FIELD_HEIGHT).asFloat());
        }
    }
    map.pushMap(bodyMap);
}
 
Example #25
Source File: Manager.java    From react-native-fitness with MIT License 5 votes vote down vote up
private void processDistance(DataSet dataSet, WritableArray map) {

        WritableMap distanceMap = Arguments.createMap();

        for (DataPoint dp : dataSet.getDataPoints()) {
            for(Field field : dp.getDataType().getFields()) {
                distanceMap.putString("startDate", dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
                distanceMap.putString("endDate", dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)));
                distanceMap.putDouble("quantity", dp.getValue(field).asFloat());
                map.pushMap(distanceMap);
            }
        }
    }
 
Example #26
Source File: Manager.java    From react-native-fitness with MIT License 5 votes vote down vote up
private void processCalories(DataSet dataSet, WritableArray map) {

        WritableMap caloryMap = Arguments.createMap();

        for (DataPoint dp : dataSet.getDataPoints()) {
            for(Field field : dp.getDataType().getFields()) {
                caloryMap.putString("startDate", dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
                caloryMap.putString("endDate", dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)));
                caloryMap.putDouble("quantity", dp.getValue(field).asFloat());
                map.pushMap(caloryMap);
            }
        }
    }
 
Example #27
Source File: Manager.java    From react-native-fitness with MIT License 5 votes vote down vote up
private void processHeartRate(DataSet dataSet, WritableArray map) {

        WritableMap heartRateMap = Arguments.createMap();

        for (DataPoint dp : dataSet.getDataPoints()) {
            for(Field field : dp.getDataType().getFields()) {
                heartRateMap.putString("startDate", dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
                heartRateMap.putString("endDate", dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)));
                heartRateMap.putDouble("quantity", dp.getValue(field).asFloat());
                map.pushMap(heartRateMap);
            }
        }
    }
 
Example #28
Source File: HydrationHistory.java    From react-native-google-fit with MIT License 5 votes vote down vote up
private void processDataSet(DataSet dataSet, WritableArray map) {
  for (DataPoint dp : dataSet.getDataPoints()) {
    WritableMap hydrationMap = Arguments.createMap();
    Value hydration = dp.getValue((Field.FIELD_VOLUME));

    hydrationMap.putDouble("date", dp.getEndTime(TimeUnit.MILLISECONDS));
    hydrationMap.putDouble("waterConsumed", hydration.asFloat());
    hydrationMap.putString("addedBy", dp.getOriginalDataSource().getAppPackageName());

    map.pushMap(hydrationMap);
  }
}
 
Example #29
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 #30
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;
}