Gravar dados de sono
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Seu app pode ler e gravar dados de sono granulares.
Isso inclui os estágios de sono leve, profundo, REM e sono acordado do
SleepStages
tipo enumerado. Para gravar dados de sono, você deve criar uma sessão do tipo
FitnessActivities.SLEEP
Os dados de sono devem ser encapsulados em uma sessão caso sejam exibidos nos registros do usuário
Diário no
App Google Fit.
Também é possível inserir segmentos do tipo SleepStages
na sessão:
Exemplo sem granularidade
Para registrar uma noite de sono sem granularidade de estágio, siga o exemplo abaixo.
Crie uma sessão com horário de início e término e o sono activity
.
Android
val fitnessOptions = FitnessOptions.builder()
.accessSleepSessions(FitnessOptions.ACCESS_WRITE)
.build()
// Create the sleep session
val session= Session.Builder()
.setName(sessionName)
.setIdentifier(identifier)
.setDescription(description)
.setStartTime(startTime, TimeUnit.MILLISECONDS)
.setEndTime(endTime, TimeUnit.MILLISECONDS)
.setActivity(FitnessActivities.SLEEP)
.build()
// Build the request to insert the session.
val request = SessionInsertRequest.Builder()
.setSession(session)
.build()
// Insert the session into Fit platform
Log.i(TAG, "Inserting the session with the SessionsClient")
Fitness.getSessionsClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
.insertSession(request)
.addOnSuccessListener {
Log.i(TAG,"Session insert was successful!")
}
.addOnFailureListener { e ->
Log.w(TAG, "There was a problem inserting the session", e)
}
Leia mais detalhes sobre
sessões no Android.
REST
Método HTTP
PUT
Request URL
https://www.googleapis.com/fitness/v1/users/me/sessions/identifier
Corpo da solicitação
{
"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
}
Exemplo de granularidade de estágios do sono
Para gravar o sono com granularidade de estágios, grave os dois registros de sono de nível superior.
sessão e segmentos para os diferentes estágios do sono.
Gravar segmentos de sono
Neste exemplo, vamos criar vários segmentos para representar os diversos segmentos
em uma noite de sono.
Android
val dataSource = DataSource.Builder()
.setType(DataSource.TYPE_RAW)
.setDataType(DataType.TYPE_SLEEP_SEGMENT)
.setAppPackageName(context)
// Optional but recommended for identifying the stream if you have multiple streams with the same dataType.
.setStreamName(streamName)
.build()
val dataPoints = listOf(
DataPoint.builder(dataSource)
.setTimeInterval(startTime1, endTime1, TimeUnit.MILLISECONDS)
.setField(Field.FIELD_SLEEP_SEGMENT_TYPE, SleepStages.SLEEP_LIGHT)
.build(),
DataPoint.builder(dataSource)
.setTimeInterval(startTime2, endTime2, TimeUnit.MILLISECONDS)
.setField(Field.FIELD_SLEEP_SEGMENT_TYPE, SleepStages.SLEEP_DEEP)
.build(),
DataPoint.builder(dataSource)
.setTimeInterval(startTime3, endTime3, TimeUnit.MILLISECONDS)
.setField(Field.FIELD_SLEEP_SEGMENT_TYPE, SleepStages.SLEEP_LIGHT)
.build(),
DataPoint.builder(dataSource)
.setTimeInterval(startTime4, endTime4, TimeUnit.MILLISECONDS)
.setField(Field.FIELD_SLEEP_SEGMENT_TYPE, SleepStages.SLEEP_REM)
.build(),
DataPoint.builder(dataSource)
.setTimeInterval(startTime5, endTime5, TimeUnit.MILLISECONDS)
.setField(Field.FIELD_SLEEP_SEGMENT_TYPE, SleepStages.AWAKE)
.build(),
DataPoint.builder(dataSource)
.setTimeInterval(startTime6, endTime6, TimeUnit.MILLISECONDS)
.setField(Field.FIELD_SLEEP_SEGMENT_TYPE, SleepStages.SLEEP_LIGHT)
.build()
)
val dataSet = DataSet.builder(dataSource)
.addAll(dataPoints)
.build()
REST
Primeiro, crie o dataSource
:
Método HTTP
POST
Request URL
https://www.googleapis.com/fitness/v1/users/me/dataSources
Corpo da solicitação
{
"dataStreamName": streamName,
"type": "raw",
"application": {
"detailsUrl": "http://example.com",
"name": "Foo Example App",
"version": "1"
},
"dataType": {
"name": "com.google.sleep.segment"
}
}
Em seguida, preencha o dataSet
:
Método HTTP
PATCH
Request URL
https://www.googleapis.com/fitness/v1/users/userId/dataSources/dataSourceId/datasets/datasetId
Corpo da solicitação
{
"dataSourceId": dataSourceId,
"point": [
{
"dataTypeName": "com.google.sleep.segment",
"startTimeNanos": startTime1,
"endTimeNanos": endTime1,
"value": [
{
intVal: 4 // Light sleep
}
]
},
{
"dataTypeName": "com.google.sleep.segment",
"startTimeNanos": startTime2,
"endTimeNanos": endTime2,
"value": [
{
intVal: 5 // Deep sleep
}
]
},
{
"dataTypeName": "com.google.sleep.segment",
"startTimeNanos": startTime3,
"endTimeNanos": endTime3,
"value": [
{
intVal: 4 // Light sleep
}
]
},
{
"dataTypeName": "com.google.sleep.segment",
"startTimeNanos": startTime4,
"endTimeNanos": endTime4,
"value": [
{
intVal: 6 // REM sleep
}
]
},
{
"dataTypeName": "com.google.sleep.segment",
"startTimeNanos": startTime5,
"endTimeNanos": endTime5,
"value": [
{
intVal: 1 // Awake
}
]
},
{
"dataTypeName": "com.google.sleep.segment",
"startTimeNanos": startTime6,
"endTimeNanos": endTime6,
"value": [
{
intVal: 4 // Light sleep
}
]
}
]
}
Gravar sessão de sono
Por fim, agrupe os segmentos acima inserindo uma sessão de sono. Definir o início
dessa sessão até a hora de início do primeiro segmento e a hora de término
até o horário de término do último segmento.
Android
val fitnessOptions = FitnessOptions.builder()
.accessSleepSessions(FitnessOptions.ACCESS_WRITE)
.addDataType(DataType.TYPE_SLEEP_SEGMENT, FitnessOptions.ACCESS_WRITE)
.build()
val session = Session.Builder()
.setName(sessionName)
.setIdentifier(identifier)
.setDescription(description)
.setStartTime(startTime1, TimeUnit.MILLISECONDS) // From first segment
.setEndTime(endTime6, TimeUnit.MILLISECONDS) // From last segment
.setActivity(FitnessActivities.SLEEP)
.build()
// Build the request to insert the session.
val request = SessionInsertRequest.Builder()
.setSession(session)
.addDataSet(dataset)
.build()
// Insert the session into Fit platform
Log.i(TAG, "Inserting the session in the Sessions API")
Fitness.getSessionsClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))
.insertSession(request)
.addOnSuccessListener {
Log.i(TAG,"Session insert was successful!")
}
.addOnFailureListener { e ->
Log.i(TAG, "There was a problem inserting the session", e)
}
REST
Método HTTP
PUT
Request URL
https://www.googleapis.com/fitness/v1/users/me/sessions/identifier
Corpo da solicitação
{
"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
}
Exceto em caso de indicação contrária, o conteúdo desta página é licenciado de acordo com a Licença de atribuição 4.0 do Creative Commons, e as amostras de código são licenciadas de acordo com a Licença Apache 2.0. Para mais detalhes, consulte as políticas do site do Google Developers. Java é uma marca registrada da Oracle e/ou afiliadas.
Última atualização 2025-08-31 UTC.
[null,null,["Última atualização 2025-08-31 UTC."],[[["\u003cp\u003eYour app can read and write detailed sleep data, including sleep stages (light, deep, REM, awake) using the Google Fit API.\u003c/p\u003e\n"],["\u003cp\u003eTo display sleep data in the Google Fit app's journal, encapsulate it within a session of type \u003ccode\u003eFitnessActivities.SLEEP\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eYou can optionally include granular sleep stage information within the sleep session using segments of type \u003ccode\u003eSleepStages\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eExamples are provided for writing sleep data with and without stage granularity using both Android and REST APIs.\u003c/p\u003e\n"]]],[],null,["# Write Sleep Data\n\nYour app can read and write granular sleep data.\nThis includes light sleep, deep sleep, REM, and awake sleep stages from the\n[`SleepStages`](/android/reference/com/google/android/gms/fitness/data/SleepStages)\nenumerated type. To write sleep data you must create a session of type\n[`FitnessActivities.SLEEP`](/android/reference/com/google/android/gms/fitness/FitnessActivities#SLEEP).\nSleep data must be encapsulated in a session if it is to appear in the user's\nJournal in the\n[Google Fit App](https://play.google.com/store/apps/details?id=com.google.android.apps.fitness).\n\nOptionally, insert segments of type `SleepStages` within the session:\n\n- [`SleepStages.SLEEP_LIGHT`](/android/reference/com/google/android/gms/fitness/SleepStages#SLEEP_LIGHT)\n- [`SleepStages.SLEEP_DEEP`](/android/reference/com/google/android/gms/fitness/SleepStages#SLEEP_DEEP)\n- [`SleepStages.SLEEP_REM`](/android/reference/com/google/android/gms/fitness/SleepStages#SLEEP_REM)\n- [`SleepStages.AWAKE`](/android/reference/com/google/android/gms/fitness/SleepStages#AWAKE)\n- [`SleepStages.OUT_OF_BED`](/android/reference/com/google/android/gms/fitness/SleepStages#OUT_OF_BED)\n\nNo-granularity example\n----------------------\n\nTo write a night of sleep with no stage granularity, follow the example below.\nCreate a session with start and end time, and the `activity` SLEEP. \n\n### Android\n\n```kotlin\nval fitnessOptions = FitnessOptions.builder()\n .accessSleepSessions(FitnessOptions.ACCESS_WRITE)\n .build()\n\n// Create the sleep session\nval session= Session.Builder()\n .setName(sessionName)\n .setIdentifier(identifier)\n .setDescription(description)\n .setStartTime(startTime, TimeUnit.MILLISECONDS)\n .setEndTime(endTime, TimeUnit.MILLISECONDS)\n .setActivity(FitnessActivities.SLEEP)\n .build()\n\n// Build the request to insert the session.\nval request = SessionInsertRequest.Builder()\n .setSession(session)\n .build()\n\n// Insert the session into Fit platform\nLog.i(TAG, \"Inserting the session with the SessionsClient\")\nFitness.getSessionsClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))\n .insertSession(request)\n .addOnSuccessListener {\n Log.i(TAG,\"Session insert was successful!\")\n }\n .addOnFailureListener { e -\u003e\n Log.w(TAG, \"There was a problem inserting the session\", e)\n }\n```\n\nRead more details about\n[sessions in Android](/android/reference/com/google/android/gms/fitness/data/Session).\n\n### REST\n\n**HTTP method** \n\n PUT\n\n**Request URL** \n\n https://www.googleapis.com/fitness/v1/users/me/sessions/identifier\n\n**Request body** \n\n {\n \"id\": identifier,\n \"name\": sessionName,\n \"description\": description,\n \"startTimeMillis\": startTime,\n \"endTimeMillis\": endTime,\n \"version\": 1,\n \"lastModifiedToken\": \"exampleToken\",\n \"application\": {\n \"detailsUrl\": \"http://example.com\",\n \"name\": \"Foo Example App\",\n \"version\": \"1.0\"\n },\n \"activityType\": 72 // Sleep\n }\n\nSleep stages granularity example\n--------------------------------\n\nTo write sleep with stages granularity, write **both** the top-level sleep\nsession and segments for the different stages of sleep.\n\n### Write sleep segments\n\nIn this example we will write several segments to represent the several sleep\nstages over one night of sleep. \n\n### Android\n\n```kotlin\nval dataSource = DataSource.Builder()\n .setType(DataSource.TYPE_RAW)\n .setDataType(DataType.TYPE_SLEEP_SEGMENT)\n .setAppPackageName(context)\n // Optional but recommended for identifying the stream if you have multiple streams with the same dataType.\n .setStreamName(streamName)\n .build()\n\nval dataPoints = listOf(\n DataPoint.builder(dataSource)\n .setTimeInterval(startTime1, endTime1, TimeUnit.MILLISECONDS)\n .setField(Field.FIELD_SLEEP_SEGMENT_TYPE, SleepStages.SLEEP_LIGHT)\n .build(),\n DataPoint.builder(dataSource)\n .setTimeInterval(startTime2, endTime2, TimeUnit.MILLISECONDS)\n .setField(Field.FIELD_SLEEP_SEGMENT_TYPE, SleepStages.SLEEP_DEEP)\n .build(),\n DataPoint.builder(dataSource)\n .setTimeInterval(startTime3, endTime3, TimeUnit.MILLISECONDS)\n .setField(Field.FIELD_SLEEP_SEGMENT_TYPE, SleepStages.SLEEP_LIGHT)\n .build(),\n DataPoint.builder(dataSource)\n .setTimeInterval(startTime4, endTime4, TimeUnit.MILLISECONDS)\n .setField(Field.FIELD_SLEEP_SEGMENT_TYPE, SleepStages.SLEEP_REM)\n .build(),\n DataPoint.builder(dataSource)\n .setTimeInterval(startTime5, endTime5, TimeUnit.MILLISECONDS)\n .setField(Field.FIELD_SLEEP_SEGMENT_TYPE, SleepStages.AWAKE)\n .build(),\n DataPoint.builder(dataSource)\n .setTimeInterval(startTime6, endTime6, TimeUnit.MILLISECONDS)\n .setField(Field.FIELD_SLEEP_SEGMENT_TYPE, SleepStages.SLEEP_LIGHT)\n .build()\n)\n\nval dataSet = DataSet.builder(dataSource)\n .addAll(dataPoints)\n .build()\n```\n\n### REST\n\n1. First create the `dataSource`:\n\n **HTTP method** \n\n POST\n\n **Request URL** \n\n https://www.googleapis.com/fitness/v1/users/me/dataSources\n\n **Request body** \n\n {\n \"dataStreamName\": streamName,\n \"type\": \"raw\",\n \"application\": {\n \"detailsUrl\": \"http://example.com\",\n \"name\": \"Foo Example App\",\n \"version\": \"1\"\n },\n \"dataType\": {\n \"name\": \"com.google.sleep.segment\"\n }\n }\n\n2. Then populate the `dataSet`:\n\n **HTTP method** \n\n PATCH\n\n **Request URL** \n\n https://www.googleapis.com/fitness/v1/users/userId/dataSources/dataSourceId/datasets/datasetId\n\n **Request body** \n\n {\n \"dataSourceId\": dataSourceId,\n \"point\": [\n {\n \"dataTypeName\": \"com.google.sleep.segment\",\n \"startTimeNanos\": startTime1,\n \"endTimeNanos\": endTime1,\n \"value\": [\n {\n intVal: 4 // Light sleep\n }\n ]\n },\n {\n \"dataTypeName\": \"com.google.sleep.segment\",\n \"startTimeNanos\": startTime2,\n \"endTimeNanos\": endTime2,\n \"value\": [\n {\n intVal: 5 // Deep sleep\n }\n ]\n },\n {\n \"dataTypeName\": \"com.google.sleep.segment\",\n \"startTimeNanos\": startTime3,\n \"endTimeNanos\": endTime3,\n \"value\": [\n {\n intVal: 4 // Light sleep\n }\n ]\n },\n {\n \"dataTypeName\": \"com.google.sleep.segment\",\n \"startTimeNanos\": startTime4,\n \"endTimeNanos\": endTime4,\n \"value\": [\n {\n intVal: 6 // REM sleep\n }\n ]\n },\n {\n \"dataTypeName\": \"com.google.sleep.segment\",\n \"startTimeNanos\": startTime5,\n \"endTimeNanos\": endTime5,\n \"value\": [\n {\n intVal: 1 // Awake\n }\n ]\n },\n {\n \"dataTypeName\": \"com.google.sleep.segment\",\n \"startTimeNanos\": startTime6,\n \"endTimeNanos\": endTime6,\n \"value\": [\n {\n intVal: 4 // Light sleep\n }\n ]\n }\n ]\n }\n\n### Write sleep session\n\nFinally, group the segments above by inserting a sleep session. Set the start\ntime for this session to the start time of the first segment, and the end time\nto the end time of the last segment. \n\n### Android\n\n```kotlin\nval fitnessOptions = FitnessOptions.builder()\n .accessSleepSessions(FitnessOptions.ACCESS_WRITE)\n .addDataType(DataType.TYPE_SLEEP_SEGMENT, FitnessOptions.ACCESS_WRITE)\n .build()\n\nval session = Session.Builder()\n .setName(sessionName)\n .setIdentifier(identifier)\n .setDescription(description)\n .setStartTime(startTime1, TimeUnit.MILLISECONDS) // From first segment\n .setEndTime(endTime6, TimeUnit.MILLISECONDS) // From last segment\n .setActivity(FitnessActivities.SLEEP)\n .build()\n\n// Build the request to insert the session.\nval request = SessionInsertRequest.Builder()\n .setSession(session)\n .addDataSet(dataset)\n .build()\n\n// Insert the session into Fit platform\nLog.i(TAG, \"Inserting the session in the Sessions API\")\nFitness.getSessionsClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))\n .insertSession(request)\n .addOnSuccessListener {\n Log.i(TAG,\"Session insert was successful!\")\n }\n .addOnFailureListener { e -\u003e\n Log.i(TAG, \"There was a problem inserting the session\", e)\n }\n```\n\n### REST\n\n**HTTP method** \n\n PUT\n\n**Request URL** \n\n https://www.googleapis.com/fitness/v1/users/me/sessions/identifier\n\n**Request body** \n\n {\n \"id\": identifier,\n \"name\": sessionName,\n \"description\": description,\n \"startTimeMillis\": startTime1,\n \"endTimeMillis\": endTime6,\n \"version\": 1,\n \"lastModifiedToken\": \"exampleToken\",\n \"application\": {\n \"detailsUrl\": \"http://example.com\",\n \"name\": \"Foo Example App\",\n \"version\": \"1.0\"\n },\n \"activityType\": 72 // Sleep\n }"]]