Las APIs de Google Fit, incluida la API de REST de Google Fit, dejarán de estar disponibles en 2026. A partir del 1 de mayo de 2024, los desarrolladores no podrán registrarse para usar estas APIs.
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Tu app puede leer y escribir datos de sueño detallados.
Esto incluye las fases de sueño ligero, sueño profundo, REM y sueño despierto de la
SleepStages
tipo enumerado. Para escribir datos de sueño, debes crear una sesión del tipo
FitnessActivities.SLEEP
Los datos de sueño se deben encapsular en una sesión si van a aparecer en la
Diario en
App de Google Fit.
De manera opcional, inserta segmentos de tipo SleepStages dentro de la sesión:
Para escribir una noche de sueño sin nivel de detalle de etapa, sigue el siguiente ejemplo.
Crea una sesión con una hora de inicio y una de finalización, y el SLEEP de activity.
Android
valfitnessOptions=FitnessOptions.builder().accessSleepSessions(FitnessOptions.ACCESS_WRITE).build()// Create the sleep sessionvalsession=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.valrequest=SessionInsertRequest.Builder().setSession(session).build()// Insert the session into Fit platformLog.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)}
Ejemplo de nivel de detalle de las etapas del sueño
Para escribir sueño con nivel de detalle de etapas, escribe ambos niveles de sueño de nivel superior.
sesión y segmentos para las diferentes etapas del sueño.
Escribir segmentos de sueño
En este ejemplo, escribiremos varios segmentos para representar los distintos segmentos de sueño
durante una noche de sueño.
Android
valdataSource=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()valdataPoints=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())valdataSet=DataSet.builder(dataSource).addAll(dataPoints).build()
Por último, agrupa los segmentos anteriores insertando una sesión de sueño. Establece el inicio
tiempo de esta sesión hasta la hora de inicio del primer segmento y la hora de finalización
hasta la hora de finalización del último segmento.
Android
valfitnessOptions=FitnessOptions.builder().accessSleepSessions(FitnessOptions.ACCESS_WRITE).addDataType(DataType.TYPE_SLEEP_SEGMENT,FitnessOptions.ACCESS_WRITE).build()valsession=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.valrequest=SessionInsertRequest.Builder().setSession(session).addDataSet(dataset).build()// Insert the session into Fit platformLog.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)}
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Falta la información que necesito","missingTheInformationINeed","thumb-down"],["Muy complicado o demasiados pasos","tooComplicatedTooManySteps","thumb-down"],["Desactualizado","outOfDate","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Problema con las muestras o los códigos","samplesCodeIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 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 }"]]