Write Sleep Data

Your app can read and write granular sleep data. This includes light sleep, deep sleep, REM, and awake activities from the FitnessActivities enumerated type. To write sleep data you must create a session of type FitnessActivities.SLEEP. Sleep data must be encapsulated in a session if it is to appear in the user’s Journal in the Google Fit App.

Optionally, insert activity segments (inside session interval) of types to represent stages of sleep

No-granularity example

To write a night of sleep with no stage granularity, follow the example below. Create a session with start and end time, and the activity SLEEP.

Android

// Create the sleep session
Session session = new Session.Builder()
    .setName(sessionName)
    .setIdentifier(identifier)
    .setDescription(description)
    .setStartTime(startTime, MILLISECONDS)
    .setEndTime(endTime, MILLISECONDS)
    .setActivity(FitnessActivities.SLEEP)
    .build();

// Build the request to insert the session.
SessionInsertRequest request = new SessionInsertRequest.Builder()
    .setSession(session)
    .build();

// Insert the session into Fit platform
Log.i(TAG, "Inserting the session in the Sessions API");
Fitness.getSessionsClient(this, GoogleSignIn.getLastSignedInAccount(this))
        .insertSession(request)
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                // At this point, the session has been inserted and can be read.
                Log.i(TAG, "Session insert was successful!");
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.i(TAG, "There was a problem inserting the session: " +
                        e.getLocalizedMessage());
            }
        });

Read more details about sessions in Android.

REST

HTTP method

POST

Request URL

https://www.googleapis.com/fitness/v1/users/me/sessions

Request body

{
    "id": identifier,
    "name": sessionName,
    "description": description,
    "startTimeMillis": startTime,
    "endTimeMillis": endTime,
    "version": 1,
    "lastModifiedToken": "exampleToken",
    "application": {
        "detailsUrl": "http://example.com",
        "name": "Foo Example App",
        "version": "1.0"
    },
    "activityType": 72 // Sleep
}

Sleep stages granularity example

To write sleep with stages granularity, write both the top-level sleep session and segments for the different stages of sleep.

Write sleep segments

In this example we will write several segments to represent the several sleep stages over one night of sleep.

Android

DataType dataType = DataTypes.ACTIVITY_SEGMENT;

DataSource dataSource = new DataSource.Builder()
    .setType(TYPE_RAW)
    .setDataType(dataType)
    .setAppPackageName(context)
    .setStreamName(streamName) // Optional but recommended for identifying the stream if you have multiple streams with the same dataType.
    .build();

DataSet dataSet = DataSet.create(dataSource);
dataSet.add(dataSet.createDataPoint()
    .setTimeInterval(startTime1, endTime1, MILLISECONDS))
    .setValues(FitnessActivities.LIGHT_SLEEP)); // Light sleep
dataSet.add(dataSet.createDataPoint()
    .setTimeInterval(startTime2, endTime2, MILLISECONDS))
    .setValues(FitnessActivities.DEEP_SLEEP)); // Deep sleep
dataSet.add(dataSet.createDataPoint()
    .setTimeInterval(startTime3, endTime3, MILLISECONDS))
    .setValues(FitnessActivities.LIGHT_SLEEP)); // Light sleep
dataSet.add(dataSet.createDataPoint()
    .setTimeInterval(startTime4, endTime4, MILLISECONDS))
    .setValues(FitnessActivities.REM_SLEEP)); // REM sleep
dataSet.add(dataSet.createDataPoint()
    .setTimeInterval(startTime5, endTime5, MILLISECONDS))
    .setValues(FitnessActivities.AWAKE)); // Awake
dataSet.add(dataSet.createDataPoint()
    .setTimeInterval(startTime6, endTime6, MILLISECONDS))
    .setValues(FitnessActivities.LIGHT_SLEEP)); // Light sleep

REST

  1. First create the dataSource:

    HTTP method

    POST
    

    Request URL

    https://www.googleapis.com/fitness/v1/users/me/datasources
    

    Request body

    {
      "dataStreamName": streamName,
      "type": "raw",
      "application": {
        "detailsUrl": "http://example.com",
        "name": "Foo Example App",
        "version": "1"
      },
      "dataType": {
        "name": "com.google.activity.segment",
        "field": [
          {
            "name": "activity",
            "format": "integer"
          }
        ]
      }
    }
    
  2. Then populate the dataSet:

    HTTP method

    PATCH
    

    Request URL

    https://www.googleapis.com/fitness/v1/users/userId/dataSources/dataSourceId/datasets/datasetId
    

    Request body

    {
        "dataSourceId": dataSourceId,
        "Point": [
            {
                "dataTypeName": "com.google.activity.segment",
                "startTimeMillis": startTime1,
                "endTimeMillis": endTime1,
                "value": [
                    {
                        intVal: 109 // Light sleep
                    }
                ]
            },
            {
                "dataTypeName": "com.google.activity.segment",
                "startTimeMillis": startTime2,
                "endTimeMillis": endTime2,
                "value": [
                    {
                        intVal: 110 // Deep sleep
                    }
                ]
            },
            {
                "dataTypeName": "com.google.activity.segment",
                "startTimeMillis": startTime3,
                "endTimeMillis": endTime3,
                "value": [
                    {
                        intVal: 109 // Light sleep
                    }
                ]
            },
            {
                "dataTypeName": "com.google.activity.segment",
                "startTimeMillis": startTime4,
                "endTimeMillis": endTime4,
                "value": [
                    {
                        intVal: 111 // REM sleep
                    }
                ]
            },
            {
                "dataTypeName": "com.google.activity.segment",
                "startTimeMillis": startTime5,
                "endTimeMillis": endTime5,
                "value": [
                    {
                        intVal: 112 // Awake
                    }
                ]
            },
            {
                "dataTypeName": "com.google.activity.segment",
                "startTimeMillis": startTime6,
                "endTimeMillis": endTime6,
                "value": [
                    {
                        intVal: 109 // Light sleep
                    }
                ]
            }
         ]
     }
    

Write sleep session

Finally, group the segments above by inserting a sleep session. Set the start time for this session to the start time of the first segment, and the end time to the end time of the last segment.

Android

Session session = new Session.Builder()
       .setName(sessionName)
       .setIdentifier(identifier)
       .setDescription(description)
       .setStartTime(startTime1, MILLISECONDS) // From first segment
       .setEndTime(endTime6, MILLISECONDS) // From last segment
       .setActivity(FitnessActivities.SLEEP)
       .build();

 SessionInsertRequest request = new SessionInsertRequest.Builder()
       .setSession(session)
       .addDataSet(dataSet)
       .build();

Fitness.getSessionsClient(this,
    GoogleSignIn.getLastSignedInAccount(this))
       .insertSession(request)
       .addOnSuccessListener(new OnSuccessListener<Void>() {
           @Override
           public void onSuccess(Void aVoid) {
               // At this point, the session has been inserted and can be read.
               Log.i(TAG, "Session insert was successful!");
           }
       })
       .addOnFailureListener(new OnFailureListener() {
           @Override
           public void onFailure(@NonNull Exception e) {
               Log.i(TAG, "There was a problem inserting the session: " +
                   e.getLocalizedMessage());
           }
       });

REST

HTTP method

PATCH

Request URL

https://www.googleapis.com/fitness/v1/users/userId/dataSources/dataSourceId/datasets/datasetId

Request body

{
    "id": identifier,
    "name": sessionName,
    "description": description,
    "startTimeMillis": startTime1,
    "endTimeMillis": endTime6,
    "version": 1,
    "lastModifiedToken": "exampleToken",
    "application": {
        "detailsUrl": "http://example.com",
        "name": "Foo Example App",
        "version": "1.0"
    },
    "activityType": 72 // Sleep
}

Send feedback about...