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.
Para obtener información acerca del dispositivo para una fuente de datos, usa el
DataSource.getDevice
. La información del dispositivo es útil para distinguir
sensores en diferentes dispositivos, muestra la información del dispositivo desde un sensor al
usuario o procesar datos de manera diferente según el dispositivo. Por ejemplo, podrías
Le interesa leer datos específicos del sensor de un dispositivo wearable
pero no del mismo tipo de sensor en un teléfono.
Para obtener un Device
para el dispositivo que está ejecutando tu actividad, usa el
Device.getLocalDevice
. Esto es útil cuando quieres comprobar si una fuente de datos se encuentra en el
mismo dispositivo en el que se ejecuta tu app.
Agrega un objeto de escucha
Para agregar un objeto de escucha que reciba datos sin procesar de un tipo de datos de actividad física en particular o de
una fuente de datos específica, usa el
SensorsClient.add
método:
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()));}
Quita un objeto de escucha
Para eliminar un objeto de escucha de las actualizaciones de datos sin procesar, usa el
SensorsClient.remove
método:
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,["Última actualización: 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```"]]