Đọc dữ liệu giấc ngủ
Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Giấc ngủ được biểu thị bằng số phiên
thuộc loại sleep
.
Phiên hoạt động có thể chứa các giai đoạn ngủ (không bắt buộc) có thông tin chi tiết hơn
dữ liệu giấc ngủ. Ví dụ: Nếu chế độ ngủ sáng, sâu hay ngủ mắt chuyển động nhanh
ngủ:
Giá trị các giai đoạn ngủ
Loại giai đoạn ngủ |
Giá trị |
Thức dậy (trong chu kỳ ngủ) |
1 |
Ngủ |
2 |
Nằm ngoài giường |
3 |
Vừa chợp mắt |
4 |
Ngủ sâu |
5 |
Ngủ mắt chuyển động nhanh (REM) |
6 |
Hướng dẫn ghi dữ liệu giấc ngủ cho thấy cách cả hai
dữ liệu chi tiết và không chi tiết về giấc ngủ được biểu thị trong Fit.
Android
Các mẫu sau đây sử dụng SessionClient
để truy xuất dữ liệu từ Fit cho cả hai trường hợp.
val SLEEP_STAGE_NAMES = arrayOf(
"Unused",
"Awake (during sleep)",
"Sleep",
"Out-of-bed",
"Light sleep",
"Deep sleep",
"REM sleep"
)
val request = SessionReadRequest.Builder()
.readSessionsFromAllApps()
// By default, only activity sessions are included, so it is necessary to explicitly
// request sleep sessions. This will cause activity sessions to be *excluded*.
.includeSleepSessions()
// Sleep segment data is required for details of the fine-granularity sleep, if it is present.
.read(DataType.TYPE_SLEEP_SEGMENT)
.setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
.build()
sessionsClient.readSession(request)
.addOnSuccessListener { response ->
for (session in response.sessions) {
val sessionStart = session.getStartTime(TimeUnit.MILLISECONDS)
val sessionEnd = session.getEndTime(TimeUnit.MILLISECONDS)
Log.i(TAG, "Sleep between $sessionStart and $sessionEnd")
// If the sleep session has finer granularity sub-components, extract them:
val dataSets = response.getDataSet(session)
for (dataSet in dataSets) {
for (point in dataSet.dataPoints) {
val sleepStageVal = point.getValue(Field.FIELD_SLEEP_SEGMENT_TYPE).asInt()
val sleepStage = SLEEP_STAGE_NAMES[sleepStageVal]
val segmentStart = point.getStartTime(TimeUnit.MILLISECONDS)
val segmentEnd = point.getEndTime(TimeUnit.MILLISECONDS)
Log.i(TAG, "\t* Type $sleepStage between $segmentStart and $segmentEnd")
}
}
}
}
Kiến trúc chuyển trạng thái đại diện (REST)
Việc truy xuất phiên giấc ngủ bằng API REST là quá trình gồm 2 giai đoạn:
Truy xuất danh sách các phiên
đang đặt thông số activityType
thành 72
(SLEEP
).
Lưu ý: Bạn có thể dùng startTime
và endTime
hoặc dùng pageToken
để truy xuất các phiên mới kể từ yêu cầu trước đó.
Phương thức HTTP
GET
URL yêu cầu
https://www.googleapis.com/fitness/v1/users/me/sessions?startTime=2019-12-05T00:00.000Z&endTime=2019-12-17T23:59:59.999Z&activityType=72
Đáp
Ví dụ: Phiên
câu trả lời có thể là:
{
"session": [
{
"id": "Sleep1575505620000",
"name": "Sleep",
"description": "",
"startTimeMillis": "1575505620000",
"endTimeMillis": "1575526800000",
"modifiedTimeMillis": "1575590432413",
"application": {
"packageName": "com.example.sleep_tracker"
},
"activityType": 72 // Sleep
},
{
"id": "Run2939075083",
"name": "Mud",
"description": "",
"startTimeMillis": "1576594403000",
"endTimeMillis": "1576598754000",
"modifiedTimeMillis": "1576616010143",
"application": {
"packageName": "com.example.run_tracker"
},
"activityType": 8 // Running
}
],
"deletedSession": [],
"nextPageToken": "1576598754001"
}
Để biết thông tin chi tiết về các giai đoạn ngủ trong từng phiên (nếu có), hãy sử dụng
yêu cầu sau cho mỗi phiên trong danh sách đã lọc:
Phương thức HTTP
POST
URL yêu cầu
https://www.googleapis.com/fitness/v1/users/userId/dataset:aggregate
Nội dung yêu cầu
{
"aggregateBy": [
{
"dataTypeName": "com.google.sleep.segment"
}
],
"endTimeMillis": 1575609060000,
"startTimeMillis": 1575591360000
}
Đáp
Nếu yêu cầu của bạn thành công, bạn sẽ nhận được trạng thái phản hồi HTTP 200 OK
. Nội dung phản hồi chứa bản trình bày JSON của hoạt động
phân đoạn bao gồm phiên giấc ngủ. Mỗi intVal
đại diện cho
loại hoạt động ngủ
{
"bucket": [
{
"startTimeMillis": "1575591360000",
"endTimeMillis": "1575609060000",
"dataset": [
{
"point": [
{
"startTimeNanos": "1575591360000000000",
"endTimeNanos": "1575595020000000000",
"dataTypeName": "com.google.sleep.segment",
"originDataSourceId": "...",
"value": [
{
"intVal": 4, // Light sleep
"mapVal": []
}
]
},
{
"startTimeNanos": "1575595020000000000",
"endTimeNanos": "1575596220000000000",
"dataTypeName": "com.google.sleep.segment",
"originDataSourceId": "...",
"value": [
{
"intVal": 1, // Sleep
"mapVal": []
}
]
},
// .... more datapoints
{
"startTimeNanos": "1575605940000000000",
"endTimeNanos": "1575609060000000000",
"dataTypeName": "com.google.sleep.segment",
"originDataSourceId": "...",
"value": [
{
"intVal": 4, // Light sleep
"mapVal": []
}
]
}
]
}
]
}
]
}
Trừ phi có lưu ý khác, nội dung của trang này được cấp phép theo Giấy phép ghi nhận tác giả 4.0 của Creative Commons và các mẫu mã lập trình được cấp phép theo Giấy phép Apache 2.0. Để biết thông tin chi tiết, vui lòng tham khảo Chính sách trang web của Google Developers. Java là nhãn hiệu đã đăng ký của Oracle và/hoặc các đơn vị liên kết với Oracle.
Cập nhật lần gần đây nhất: 2025-08-31 UTC.
[null,null,["Cập nhật lần gần đây nhất: 2025-08-31 UTC."],[[["\u003cp\u003eSleep data in Google Fit is stored as sessions of type \u003ccode\u003esleep\u003c/code\u003e and can optionally contain detailed sleep stage information.\u003c/p\u003e\n"],["\u003cp\u003eSleep stages are categorized with specific values, such as 1 for awake, 4 for light sleep, and 6 for REM sleep.\u003c/p\u003e\n"],["\u003cp\u003eAndroid developers can use the \u003ccode\u003eSessionClient\u003c/code\u003e and \u003ccode\u003eSessionReadRequest\u003c/code\u003e to retrieve both basic and detailed sleep data.\u003c/p\u003e\n"],["\u003cp\u003eREST API access involves a two-step process: retrieving a list of sleep sessions, then requesting detailed sleep stage data for each session if available.\u003c/p\u003e\n"],["\u003cp\u003eSleep stage details from the REST API are provided as \u003ccode\u003eintVal\u003c/code\u003e values within the response, corresponding to the sleep stage categories.\u003c/p\u003e\n"]]],[],null,["# Read Sleep Data\n\nSleep is represented by [sessions](https://developers.google.com/fit/rest/v1/using-sessions)\nof type [`sleep`](https://developers.google.com/fit/rest/v1/reference/activity-types).\nSessions can optionally contain sleep stages, which have more granular details\nabout sleep data. For example, if it was light, deep or REM\nsleep:\n\n##### Sleep stage values\n\n| Sleep stage type | Value |\n|----------------------------|-------|\n| Awake (during sleep cycle) | 1 |\n| Sleep | 2 |\n| Out-of-bed | 3 |\n| Light sleep | 4 |\n| Deep sleep | 5 |\n| REM | 6 |\n\nThe [write sleep data](/fit/scenarios/write-sleep-data) guide shows how both\ngranular and non-granular sleep data is represented in Fit. \n\n### Android\n\nThe follow samples uses a [SessionClient](https://developers.google.com/android/reference/com/google/android/gms/fitness/SessionsClient.html)\nto retrieve data from Fit, for both cases. \n\n```kotlin\nval SLEEP_STAGE_NAMES = arrayOf(\n \"Unused\",\n \"Awake (during sleep)\",\n \"Sleep\",\n \"Out-of-bed\",\n \"Light sleep\",\n \"Deep sleep\",\n \"REM sleep\"\n)\n\nval request = SessionReadRequest.Builder()\n .readSessionsFromAllApps()\n // By default, only activity sessions are included, so it is necessary to explicitly\n // request sleep sessions. This will cause activity sessions to be *excluded*.\n .includeSleepSessions()\n // Sleep segment data is required for details of the fine-granularity sleep, if it is present.\n .read(DataType.TYPE_SLEEP_SEGMENT)\n .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)\n .build()\n\nsessionsClient.readSession(request)\n .addOnSuccessListener { response -\u003e\n for (session in response.sessions) {\n val sessionStart = session.getStartTime(TimeUnit.MILLISECONDS)\n val sessionEnd = session.getEndTime(TimeUnit.MILLISECONDS)\n Log.i(TAG, \"Sleep between $sessionStart and $sessionEnd\")\n\n // If the sleep session has finer granularity sub-components, extract them:\n val dataSets = response.getDataSet(session)\n for (dataSet in dataSets) {\n for (point in dataSet.dataPoints) {\n val sleepStageVal = point.getValue(Field.FIELD_SLEEP_SEGMENT_TYPE).asInt()\n val sleepStage = SLEEP_STAGE_NAMES[sleepStageVal]\n val segmentStart = point.getStartTime(TimeUnit.MILLISECONDS)\n val segmentEnd = point.getEndTime(TimeUnit.MILLISECONDS)\n Log.i(TAG, \"\\t* Type $sleepStage between $segmentStart and $segmentEnd\")\n }\n }\n }\n }\n```\n\n### REST\n\nRetrieving sleep sessions using the REST API is a two stage process:\n\n1. [Retrieve a list of sessions](https://developers.google.com/fit/rest/v1/using-sessions#list_existing_sessions)\n setting the [`activityType`](https://developers.google.com/fit/rest/v1/reference/activity-types) parameter to `72` (`SLEEP`).\n Note: You can use a `startTime` and `endTime`, or use a [pageToken](https://developers.google.com/fit/rest/v1/reference/users/sessions/list#parameters)\n to retrieve new sessions since the previous request.\n\n **HTTP method** \n\n GET\n\n **Request URL** \n\n https://www.googleapis.com/fitness/v1/users/me/sessions?startTime=2019-12-05T00:00.000Z&endTime=2019-12-17T23:59:59.999Z&activityType=72\n\n **Response**\n\n An example [Session](https://developers.google.com/fit/rest/v1/reference/users/sessions/list#response_1)\n response might be: \n\n {\n \"session\": [\n {\n \"id\": \"Sleep1575505620000\",\n \"name\": \"Sleep\",\n \"description\": \"\",\n \"startTimeMillis\": \"1575505620000\",\n \"endTimeMillis\": \"1575526800000\",\n \"modifiedTimeMillis\": \"1575590432413\",\n \"application\": {\n \"packageName\": \"com.example.sleep_tracker\"\n },\n \"activityType\": 72 // Sleep\n },\n {\n \"id\": \"Run2939075083\",\n \"name\": \"Mud\",\n \"description\": \"\",\n \"startTimeMillis\": \"1576594403000\",\n \"endTimeMillis\": \"1576598754000\",\n \"modifiedTimeMillis\": \"1576616010143\",\n \"application\": {\n \"packageName\": \"com.example.run_tracker\"\n },\n \"activityType\": 8 // Running\n }\n ],\n \"deletedSession\": [],\n \"nextPageToken\": \"1576598754001\"\n }\n\n2. To obtain details of sleep stages for each session (if present), use the\n following request for each session in the filtered list:\n\n **HTTP method** \n\n POST\n\n **Request URL** \n\n https://www.googleapis.com/fitness/v1/users/userId/dataset:aggregate\n\n **Request body** \n\n {\n \"aggregateBy\": [\n {\n \"dataTypeName\": \"com.google.sleep.segment\"\n }\n ],\n \"endTimeMillis\": 1575609060000,\n \"startTimeMillis\": 1575591360000\n }\n\n **Response**\n\n If your request was successful, you'll get a `200 OK` HTTP response status\n code. The response body contains a JSON representation of activity\n segments that comprise the sleep session. Each `intVal` represents the\n sleep [activity type](#sleep_activity_values) \n\n {\n \"bucket\": [\n {\n \"startTimeMillis\": \"1575591360000\",\n \"endTimeMillis\": \"1575609060000\",\n \"dataset\": [\n {\n \"point\": [\n {\n \"startTimeNanos\": \"1575591360000000000\",\n \"endTimeNanos\": \"1575595020000000000\",\n \"dataTypeName\": \"com.google.sleep.segment\",\n \"originDataSourceId\": \"...\",\n \"value\": [\n {\n \"intVal\": 4, // Light sleep\n \"mapVal\": []\n }\n ]\n },\n {\n \"startTimeNanos\": \"1575595020000000000\",\n \"endTimeNanos\": \"1575596220000000000\",\n \"dataTypeName\": \"com.google.sleep.segment\",\n \"originDataSourceId\": \"...\",\n \"value\": [\n {\n \"intVal\": 1, // Sleep\n \"mapVal\": []\n }\n ]\n },\n\n // .... more datapoints\n\n {\n \"startTimeNanos\": \"1575605940000000000\",\n \"endTimeNanos\": \"1575609060000000000\",\n \"dataTypeName\": \"com.google.sleep.segment\",\n \"originDataSourceId\": \"...\",\n \"value\": [\n {\n \"intVal\": 4, // Light sleep\n \"mapVal\": []\n }\n ]\n }\n ]\n }\n ]\n }\n ]\n }"]]