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)}
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()
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)}
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["没有我需要的信息","missingTheInformationINeed","thumb-down"],["太复杂/步骤太多","tooComplicatedTooManySteps","thumb-down"],["内容需要更新","outOfDate","thumb-down"],["翻译问题","translationIssue","thumb-down"],["示例/代码问题","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-07-25。"],[[["\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,["Your 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\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\nAndroid \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\nREST\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\nTo write sleep with stages granularity, write **both** the top-level sleep\nsession and segments for the different stages of sleep.\n\nWrite sleep segments\n\nIn this example we will write several segments to represent the several sleep\nstages over one night of sleep. \n\nAndroid \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\nREST\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\nWrite 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\nAndroid \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\nREST\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 }"]]