Les API Google Fit, y compris l'API REST Google Fit, seront abandonnées en 2026. Depuis le 1er mai 2024, les développeurs ne peuvent plus s'inscrire pour utiliser ces API.
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
L'API Sensors vous permet de lire les données brutes des capteurs dans votre application en temps réel. Utilisez
cette API pour effectuer les opérations suivantes:
Listez les sources de données disponibles sur l'appareil et sur les appareils associés.
Enregistrez les écouteurs pour recevoir les données brutes des capteurs.
Désinscrivez les écouteurs afin qu'ils ne reçoivent plus les données brutes des capteurs.
Lister les sources de données disponibles
Obtenir la liste de toutes les sources de données disponibles sur l'appareil et sur l'application associée
appareils, utilisez la
SensorsClient.findDataSources
méthode:
Pour obtenir des informations sur l'appareil en vue d'une source de données, utilisez la méthode
DataSource.getDevice
. Ces informations sont utiles pour distinguer
les capteurs de différents appareils, afficher les informations provenant d'un capteur
utilisateur ou traiter les données différemment selon l'appareil. Par exemple, vous pouvez
lire les données à partir du capteur d'un accessoire connecté
d'un appareil, mais pas du même type de capteur sur un téléphone.
Pour obtenir une Device
pour l'appareil qui exécute votre activité, utilisez la
Device.getLocalDevice
. Cela s'avère utile lorsque vous souhaitez vérifier si une source de données se trouve sur
sur le même appareil que celui
sur lequel votre application s'exécute.
Ajouter un écouteur
Pour ajouter un écouteur afin de recevoir des données brutes d'un type particulier de données de remise en forme
une source de données spécifique, utilisez la méthode
SensorsClient.add
méthode:
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()));}
Supprimer un écouteur
Pour supprimer un écouteur des mises à jour de données brutes, utilisez la méthode
SensorsClient.remove
méthode:
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."));
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/08/31 (UTC).
[null,null,["Dernière mise à jour le 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```"]]