Các API của Google Fit, bao gồm cả API Google Fit REST, sẽ ngừng hoạt động vào năm 2026. Kể từ ngày 1 tháng 5 năm 2024, nhà phát triển không thể đăng ký sử dụng các API này.
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.
API Cảm biến cho phép bạn đọc dữ liệu cảm biến thô trong ứng dụng của mình theo thời gian thực. Sử dụng
API này để thực hiện những việc sau:
Liệt kê các nguồn dữ liệu có trên thiết bị và trên các thiết bị đồng hành.
Đăng ký trình nghe để nhận dữ liệu cảm biến thô.
Huỷ đăng ký trình nghe để trình nghe không còn nhận được dữ liệu cảm biến thô.
Liệt kê nguồn dữ liệu có sẵn
Để lấy danh sách tất cả các nguồn dữ liệu có sẵn trên thiết bị và trên quảng cáo đồng hành
thiết bị di động, hãy sử dụng
SensorsClient.findDataSources
phương thức:
Để nhận thông tin về thiết bị cho một nguồn dữ liệu, hãy sử dụng
DataSource.getDevice
. Thông tin thiết bị rất hữu ích để phân biệt với
cảm biến trên các thiết bị khác nhau, hiển thị thông tin thiết bị từ cảm biến đến
hoặc xử lý dữ liệu theo cách khác nhau dựa trên thiết bị. Ví dụ: bạn có thể
muốn đọc dữ liệu đặc biệt từ cảm biến trên thiết bị đeo
nhưng không phải từ cùng một loại cảm biến trên điện thoại.
Cách nhận Device
cho thiết bị đang chạy hoạt động của bạn, hãy sử dụng
Device.getLocalDevice
. Điều này rất hữu ích khi bạn muốn kiểm tra xem nguồn dữ liệu có nằm trên
cùng thiết bị mà ứng dụng của bạn đang chạy trên đó.
Thêm trình nghe
Để thêm một trình nghe để nhận dữ liệu thô của một loại dữ liệu thể dục cụ thể hoặc từ
một nguồn dữ liệu cụ thể, hãy sử dụng
SensorsClient.add
phương thức:
Kotlin
vallistener=OnDataPointListener{dataPoint->
for(fieldindataPoint.dataType.fields){valvalue=dataPoint.getValue(field)Log.i(TAG,"Detected DataPoint field: ${field.name}")Log.i(TAG,"Detected DataPoint value: $value")}}Fitness.getSensorsClient(this,GoogleSignIn.getAccountForExtension(this,fitnessOptions)).add(SensorRequest.Builder().setDataSource(dataSource)// Optional but recommended for custom// data sets..setDataType(dataType)// Can't be omitted..setSamplingRate(10,TimeUnit.SECONDS).build(),listener).addOnSuccessListener{Log.i(TAG,"Listener registered!")}.addOnFailureListener{Log.e(TAG,"Listener not registered.",task.exception)}
Java
OnDataPointListenerlistener=dataPoint->{for(Fieldfield:dataPoint.getDataType().getFields()){Valuevalue=dataPoint.getValue(field);Log.i(TAG,"Detected DataPoint field: ${field.getName()}");Log.i(TAG,"Detected DataPoint value: $value");}};Fitness.getSensorsClient(this,GoogleSignIn.getAccountForExtension(this,fitnessOptions)).add(newSensorRequest.Builder().setDataSource(dataSource)// Optional but recommended// for custom data sets..setDataType(dataType)// Can't be omitted..setSamplingRate(10,TimeUnit.SECONDS).build(),listener).addOnSuccessListener(unused->
Log.i(TAG,"Listener registered!")).addOnFailureListener(task->
Log.e(TAG,"Listener not registered.",task.getCause()));}
Xoá một trình nghe
Để xoá một trình nghe khỏi cập nhật dữ liệu thô, hãy sử dụng
SensorsClient.remove
phương thức:
Kotlin
Fitness.getSensorsClient(this,GoogleSignIn.getAccountForExtension(this,fitnessOptions)).remove(listener).addOnSuccessListener{Log.i(TAG,"Listener was removed!")}.addOnFailureListener{Log.i(TAG,"Listener was not removed.")}
Java
Fitness.getSensorsClient(this,GoogleSignIn.getAccountForExtension(this,fitnessOptions)).remove(listener).addOnSuccessListener(unused->
Log.i(TAG,"Listener was removed!")).addOnFailureListener(e->
Log.i(TAG,"Listener was not removed."));
[null,null,["Cập nhật lần gần đây nhất: 2025-08-31 UTC."],[[["\u003cp\u003eThe Sensors API enables real-time access to raw sensor data from a device and connected wearables, offering functionalities to list data sources, register data listeners, and manage these listeners.\u003c/p\u003e\n"],["\u003cp\u003eDevelopers can identify available data sources, such as step count, using \u003ccode\u003eSensorsClient.findDataSources\u003c/code\u003e, with the option to filter by data type and device for targeted data retrieval.\u003c/p\u003e\n"],["\u003cp\u003eReal-time data updates can be received by attaching a listener using \u003ccode\u003eSensorsClient.add\u003c/code\u003e, defining data types, sources, and sampling rates, for immediate data processing or visualization within the app.\u003c/p\u003e\n"],["\u003cp\u003eTo stop data updates, developers can detach a listener using \u003ccode\u003eSensorsClient.remove\u003c/code\u003e, ceasing the flow of raw sensor data to the specified listener, freeing resources, and halting real-time processing.\u003c/p\u003e\n"],["\u003cp\u003eIt is important to note that sensor data is not automatically stored; the Recording API is recommended for background data recording, while the Sensors API is best suited for immediate display and processing of sensor data.\u003c/p\u003e\n"]]],[],null,["# Access raw sensor data\n\nThe Sensors API lets you read raw sensor data in your app in real time. Use\nthis API to do the following:\n\n- List data sources that are available on the device and on companion devices.\n- Register listeners to receive raw sensor data.\n- Unregister listeners so that they no longer receive raw sensor data.\n\n| **Caution:** The Sensors API doesn't automatically store sensor readings in the fitness store, and sensor registrations created with the Sensors API aren't persisted when the system restarts. It's typical to use the [Recording API](/fit/android/record) to record data in the background with persistent subscriptions; use the Sensors API to display or process sensor readings in real time. In many cases, both of these APIs need to be used in an app.\n| **Note:** For best practices when you manage user data, see [Google Fit Developer and User Data Policy](/fit/policy).\n\nList available data sources\n---------------------------\n\nTo obtain a list of all available data sources on the device and on companion\ndevices, use the\n[`SensorsClient.findDataSources`](/android/reference/com/google/android/gms/fitness/SensorsClient#public-tasklistdatasource-finddatasources-datasourcesrequest-request)\nmethod: \n\n### Kotlin\n\n```kotlin\nprivate val fitnessOptions = FitnessOptions.builder().addDataType(DataType.TYPE_STEP_COUNT_DELTA).build()\n\n// Note: Fitness.SensorsApi.findDataSources() requires the\n// ACCESS_FINE_LOCATION permission.\nFitness.getSensorsClient(requireContext(), GoogleSignIn.getAccountForExtension(requireContext(), fitnessOptions))\n .findDataSources(\n DataSourcesRequest.Builder()\n .setDataTypes(DataType.TYPE_STEP_COUNT_DELTA)\n .setDataSourceTypes(DataSource.TYPE_RAW)\n .build())\n .addOnSuccessListener { dataSources -\u003e\n dataSources.forEach {\n Log.i(TAG, \"Data source found: ${it.streamIdentifier}\")\n Log.i(TAG, \"Data Source type: ${it.dataType.name}\")\n\n if (it.dataType == DataType.TYPE_STEP_COUNT_DELTA) {\n Log.i(TAG, \"Data source for STEP_COUNT_DELTA found!\")\n\n ...\n }\n }\n }\n .addOnFailureListener { e -\u003e\n Log.e(TAG, \"Find data sources request failed\", e)\n }\n```\n\n### Java\n\n```java\nFitnessOptions fitnessOptions = FitnessOptions.builder().addDataType(DataType.TYPE_STEP_COUNT_DELTA).build();\n\n// Note: Fitness.SensorsApi.findDataSources() requires the\n// ACCESS_FINE_LOCATION permission.\nFitness.getSensorsClient(getApplicationContext(), GoogleSignIn.getAccountForExtension(getApplicationContext(), fitnessOptions))\n .findDataSources(\n new DataSourcesRequest.Builder()\n .setDataTypes(DataType.TYPE_STEP_COUNT_DELTA)\n .setDataSourceTypes(DataSource.TYPE_RAW)\n .build())\n .addOnSuccessListener(dataSources -\u003e {\n dataSources.forEach(dataSource -\u003e {\n Log.i(TAG, \"Data source found: ${it.streamIdentifier}\");\n Log.i(TAG, \"Data Source type: ${it.dataType.name}\");\n\n if (dataSource.getDataType() == DataType.TYPE_STEP_COUNT_DELTA) {\n Log.i(TAG, \"Data source for STEP_COUNT_DELTA found!\");\n ...\n }\n })})\n .addOnFailureListener(e -\u003e\n Log.e(TAG, \"Find data sources request failed\", e));\n```\n\nTo get information about the device for a data source, use the\n[`DataSource.getDevice`](/android/reference/com/google/android/gms/fitness/data/DataSource#public-device-getdevice)\nmethod. The device information is useful to distinguish from similar\nsensors on different devices, show the device information from a sensor to the\nuser, or process data differently based on the device. For example, you might\nbe interested in reading data specifically from the sensor on a wearable\ndevice but not from the same type of sensor on a phone.\n\nTo get a [`Device`](/android/reference/com/google/android/gms/fitness/data/Device)\ninstance for the device that's running your activity, use the\n[`Device.getLocalDevice`](/android/reference/com/google/android/gms/fitness/data/Device#public-static-device-getlocaldevice-context-context)\nmethod. This is useful when you want to check whether a data source is on the\nsame device that your app is running on.\n\nAdd a listener\n--------------\n\nTo add a listener to receive raw data of a particular fitness data type or from\na specific data source, use the\n[`SensorsClient.add`](/android/reference/com/google/android/gms/fitness/SensorsClient#public-taskvoid-add-sensorrequest-request,-ondatapointlistener-listener)\nmethod: \n\n### Kotlin\n\n```kotlin\nval listener = OnDataPointListener { dataPoint -\u003e\n for (field in dataPoint.dataType.fields) {\n val value = dataPoint.getValue(field)\n Log.i(TAG, \"Detected DataPoint field: ${field.name}\")\n Log.i(TAG, \"Detected DataPoint value: $value\")\n }\n }\n\nFitness.getSensorsClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))\n .add(\n SensorRequest.Builder()\n .setDataSource(dataSource) // Optional but recommended for custom\n // data sets.\n .setDataType(dataType) // Can't be omitted.\n .setSamplingRate(10, TimeUnit.SECONDS)\n .build(),\n listener\n )\n .addOnSuccessListener {\n \tLog.i(TAG, \"Listener registered!\")\n }\n .addOnFailureListener {\n \tLog.e(TAG, \"Listener not registered.\", task.exception)\n }\n```\n\n### Java\n\n```java\nOnDataPointListener listener = dataPoint -\u003e {\n for (Field field : dataPoint.getDataType().getFields()) {\n Value value = dataPoint.getValue(field);\n Log.i(TAG, \"Detected DataPoint field: ${field.getName()}\");\n Log.i(TAG, \"Detected DataPoint value: $value\");\n }\n};\nFitness.getSensorsClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))\n .add(\n new SensorRequest.Builder()\n .setDataSource(dataSource) // Optional but recommended\n // for custom data sets.\n .setDataType(dataType) // Can't be omitted.\n .setSamplingRate(10, TimeUnit.SECONDS)\n .build(),\n listener\n )\n .addOnSuccessListener(unused -\u003e\n Log.i(TAG, \"Listener registered!\"))\n .addOnFailureListener(task -\u003e\n Log.e(TAG, \"Listener not registered.\", task.getCause()));\n}\n```\n\nRemove a listener\n-----------------\n\nTo remove a listener from raw data updates, use the\n[`SensorsClient.remove`](/android/reference/com/google/android/gms/fitness/SensorsClient#public-taskboolean-remove-ondatapointlistener-listener)\nmethod: \n\n### Kotlin\n\n```kotlin\nFitness.getSensorsClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))\n .remove(listener)\n .addOnSuccessListener {\n \tLog.i(TAG, \"Listener was removed!\")\n }\n .addOnFailureListener {\n \tLog.i(TAG, \"Listener was not removed.\")\n }\n```\n\n### Java\n\n```java\nFitness.getSensorsClient(this, GoogleSignIn.getAccountForExtension(this, fitnessOptions))\n .remove(listener)\n .addOnSuccessListener(unused -\u003e\n Log.i(TAG, \"Listener was removed!\"))\n .addOnFailureListener(e -\u003e\n Log.i(TAG, \"Listener was not removed.\"));\n```"]]