AndroidDevM10 AndroidDevM10 - 2 years ago 118
Java Question

How to get the user's current speed using Google Fit's API?

Working with the Google Fit API at the moment and having a bit of trouble with the Sensors API. I'm trying to get user's current speed for my app's workouts but the documentation is a bit confusing.

In this code snippet is an example from Google's info page:

new SensorRequest.Builder()
// Optional but recommended for custom data sets.
.setDataType(DataType.TYPE_SPEED)// Can't be omitted.
.setSamplingRate(1, TimeUnit.SECONDS).setAccuracyMode(SensorRequest.ACCURACY_MODE_HIGH)
.build(), mListener3)
.setResultCallback(new ResultCallback<Status>() {
public void onResult(Status status) {
if (status.isSuccess()) {
Log.i(TAG, "Listener registered!");
} else {
Log.i(TAG, "Listener not registered.");

//Adding a Listener

mListener3 = new OnDataPointListener() {
public void onDataPoint(DataPoint dataPoint) {

final float speed = dataPoint.getValue(Field.FIELD_SPEED).asFloat();

runOnUiThread(new Runnable() {
public void run() {

Log.i(TAG, "In Speed" + speed );
speedTxtView.setText("" + speed );



Currently, I am getting all other datatype values like distance, heart rate ,step count and current activity but unable to get user's current speed.
Is i am doing correctly?

Answer Source

You could try the basichistorysessions sample from Google Fit Github repository.

sample code:

  // Build a session read request
        SessionReadRequest readRequest = new SessionReadRequest.Builder()
                .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)

// Invoke the Sessions API to fetch the session with the query and wait for the result
                    // of the read request.
                    SessionReadResult sessionReadResult =
                            Fitness.SessionsApi.readSession(mClient, readRequest)
                                    .await(1, TimeUnit.MINUTES);

                    // Get a list of the sessions that match the criteria to check the result.
                    Log.i(TAG, "Session read was successful. Number of returned sessions is: "
                            + sessionReadResult.getSessions().size());
                    for (Session session : sessionReadResult.getSessions()) {
                        // Process the session

                        // Process the data sets for this session
                        List<DataSet> dataSets = sessionReadResult.getDataSet(session);
                        for (DataSet dataSet : dataSets) {

You can refer to this reading fitness data using sessions section for more information.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download