As APIs do Google Fit, incluindo a API REST do Google Fit, serão descontinuadas em 2026. A partir de 1º de maio de 2024, os desenvolvedores não poderão se inscrever para usar essas APIs.
Para obter informações sobre o dispositivo para uma fonte de dados, use o
DataSource.getDevice
. As informações do dispositivo são úteis para diferenciar de similares
em diferentes dispositivos, mostram as informações do dispositivo de um sensor para o
ou processam os dados de maneira diferente com base no dispositivo. Por exemplo, talvez você
em ler dados especificamente do sensor em um dispositivo
mas não do mesmo tipo de sensor em um smartphone.
Para receber um Device
instância para o dispositivo que está executando sua atividade, use o
Device.getLocalDevice
. Isso é útil quando você deseja verificar se uma fonte de dados está no
no mesmo dispositivo em que o app está sendo executado.
Adicionar um listener
Para adicionar um listener para receber dados brutos de um tipo específico de dados de condicionamento físico ou de
uma fonte de dados específica, use o
SensorsClient.add
:
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()));}
Remover um listener
Para remover um listener das atualizações de dados brutos, use o método
SensorsClient.remove
:
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 atualização 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```"]]