Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
La API de Bluetooth admite el trabajo con perfiles de Bluetooth. R
El perfil de Bluetooth es una especificación de interfaz inalámbrica para conexiones Bluetooth
la comunicación entre dispositivos, como el perfil de manos libres. Para dispositivos móviles
para conectarse a auriculares inalámbricos, ambos dispositivos deben ser compatibles con
Perfil de manos libres.
La API de Bluetooth ofrece implementaciones para los siguientes dispositivos Bluetooth
perfiles:
Auriculares El perfil de auriculares permite usar los auriculares Bluetooth
que se usan con teléfonos celulares. Android proporciona la
clase BluetoothHeadset,
que es un proxy para controlar el servicio de auriculares Bluetooth. Esto incluye
perfiles de manos libres (v1.5) y auriculares Bluetooth. El BluetoothHeadset
incluye compatibilidad con comandos de AT. Para obtener más información sobre este tema, consulta
Comandos de AT específicos del proveedor.
A2DP El perfil de distribución de audio avanzada (A2DP) define la manera en que
Se puede transmitir audio de alta calidad de un dispositivo a otro a través de Bluetooth.
conexión. Android proporciona la
BluetoothA2dp, que es
un proxy para controlar el servicio de A2DP de Bluetooth.
Dispositivo de salud. Android admite el dispositivo de salud Bluetooth
Perfil (HDP). Esta opción te permite crear apps que se comunican mediante Bluetooth
en dispositivos de salud compatibles con Bluetooth, como monitores de frecuencia cardíaca,
medidores, termómetros, básculas, etcétera. Para obtener una lista de los dispositivos
los códigos de especialización de datos del dispositivo correspondientes; consulta el HDP de Bluetooth
Datos del dispositivo
Especializaciones.
También se hace referencia a estos valores en la especificación ISO/IEEE 11073-20601 [7]
como MDC_DEV_SPEC_PROFILE_* en el Anexo de Códigos de Nomenclatura. Para ver más
para obtener información sobre el HDP, consulta Perfil de dispositivos de salud.
A continuación, se detallan los pasos básicos para trabajar con un perfil:
Usa
getProfileProxy()
para establecer una conexión con el objeto del proxy de perfil asociado al
perfil. En el siguiente ejemplo, el objeto del proxy de perfil es una instancia de
BluetoothHeadset
En
onServiceConnected():
para obtener un handle para el objeto del proxy de perfil.
Una vez que tienes el objeto del proxy de perfil, úsalo para supervisar el estado del
y realizar otras operaciones relevantes para ese perfil.
En el siguiente fragmento de código, se muestra cómo conectarse a un proxy BluetoothHeadset
objeto para que puedas controlar el perfil de auriculares:
Kotlin
varbluetoothHeadset:BluetoothHeadset? =null// Get the default adaptervalbluetoothAdapter:BluetoothAdapter? =BluetoothAdapter.getDefaultAdapter()privatevalprofileListener=object:BluetoothProfile.ServiceListener{overridefunonServiceConnected(profile:Int,proxy:BluetoothProfile){if(profile==BluetoothProfile.HEADSET){bluetoothHeadset=proxyasBluetoothHeadset}}overridefunonServiceDisconnected(profile:Int){if(profile==BluetoothProfile.HEADSET){bluetoothHeadset=null}}}// Establish connection to the proxy.bluetoothAdapter?.getProfileProxy(context,profileListener,BluetoothProfile.HEADSET)// ... call functions on bluetoothHeadset// Close proxy connection after use.bluetoothAdapter?.closeProfileProxy(BluetoothProfile.HEADSET,bluetoothHeadset)
Java
BluetoothHeadsetbluetoothHeadset;// Get the default adapterBluetoothAdapterbluetoothAdapter=BluetoothAdapter.getDefaultAdapter();privateBluetoothProfile.ServiceListenerprofileListener=newBluetoothProfile.ServiceListener(){publicvoidonServiceConnected(intprofile,BluetoothProfileproxy){if(profile==BluetoothProfile.HEADSET){bluetoothHeadset=(BluetoothHeadset)proxy;}}publicvoidonServiceDisconnected(intprofile){if(profile==BluetoothProfile.HEADSET){bluetoothHeadset=null;}}};// Establish connection to the proxy.bluetoothAdapter.getProfileProxy(context,profileListener,BluetoothProfile.HEADSET);// ... call functions on bluetoothHeadset// Close proxy connection after use.bluetoothAdapter.closeProfileProxy(bluetoothHeadset);
Comandos de AT específicos del proveedor
Las apps se pueden registrar para recibir transmisiones del sistema de AT específicas de los proveedores
comandos enviados por auriculares (como un comando +XEVENT de Plantronics). Por ejemplo:
una app puede recibir transmisiones que indiquen el nivel de batería de un dispositivo conectado
y podrían notificar al usuario o tomar otras medidas según sea necesario. Crear una transmisión
receptor de la
ACTION_VENDOR_SPECIFIC_HEADSET_EVENT
para manejar los comandos de AT específicos del proveedor para los auriculares.
Cuando se usa la API de Bluetooth Health, es útil comprender estos HDP clave
conceptos:
Fuente
Un dispositivo de salud, como una báscula, un glucosímetro o un termómetro, que
transmite datos médicos a un dispositivo inteligente, como un teléfono o una tablet Android.
Receptor
El dispositivo inteligente que recibe los datos médicos En una aplicación del HDP, el
receptor se representa con un objeto BluetoothHealthAppConfiguration.
Registro
El proceso que se usa para registrar un receptor a fin de comunicarse con una salud en particular
dispositivo.
Conexión
Es el proceso que se usa para abrir un canal entre un dispositivo de salud (fuente) y un
dispositivo inteligente (receptor).
Cómo crear una app del HDP
Estos son los pasos básicos que debes seguir para crear una app del HDP:
Obtén una referencia al objeto del proxy BluetoothHealth. Al igual que con los clientes
auriculares y dispositivos de perfil A2DP, debes llamar a getProfileProxy() con un
BluetoothProfile.ServiceListener y las
Tipo de perfil de HEALTH
para establecer una conexión con el objeto del proxy de perfil.
Crea un BluetoothHealthCallback y registra una configuración de app
(BluetoothHealthAppConfiguration) que actúa como receptor de estado.
Establece una conexión con el dispositivo de salud.
Cuando te conectes correctamente a un dispositivo de salud, lee el archivo de salud y escribe en él
usando el descriptor de archivos. Los datos recibidos deben interpretarse
con un administrador de salud, que implementa la norma IEEE 11073
especificaciones del producto.
Cuando hayas terminado, cierra el canal de salud y cancela el registro de la app. El canal también
se cierra cuando hay inactividad por tiempo prolongado.
El contenido y las muestras de código que aparecen en esta página están sujetas a las licencias que se describen en la Licencia de Contenido. Java y OpenJDK son marcas registradas de Oracle o sus afiliados.
Última actualización: 2025-07-27 (UTC)
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Falta la información que necesito","missingTheInformationINeed","thumb-down"],["Muy complicado o demasiados pasos","tooComplicatedTooManySteps","thumb-down"],["Desactualizado","outOfDate","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Problema con las muestras o los códigos","samplesCodeIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-07-27 (UTC)"],[],[],null,["# Bluetooth profiles\n\nThe Bluetooth API includes support for working with Bluetooth profiles. A\nBluetooth profile is a wireless interface specification for Bluetooth-based\ncommunication between devices, such as the Hands-Free profile. For a mobile\ndevice to connect to a wireless headset, both devices must support the\nHands-Free profile.\n\nThe Bluetooth API provides implementations for the following Bluetooth\nprofiles:\n\n- **Headset** . The Headset profile provides support for Bluetooth headsets to be used with mobile phones. Android provides the [`BluetoothHeadset`](/reference/android/bluetooth/BluetoothHeadset) class, which is a proxy for controlling the Bluetooth Headset Service. This includes both Bluetooth Headset and Hands-Free (v1.5) profiles. The `BluetoothHeadset` class includes support for AT commands. For more on this topic, see [Vendor-specific AT commands](#at-commands).\n- **A2DP** . The Advanced Audio Distribution Profile (A2DP) profile defines how high-quality audio can be streamed from one device to another over a Bluetooth connection. Android provides the [`BluetoothA2dp`](/reference/android/bluetooth/BluetoothA2dp) class, which is a proxy for controlling the Bluetooth A2DP Service.\n- **Health Device** . Android provides support for the Bluetooth Health Device Profile (HDP). This lets you create apps that use Bluetooth to communicate with health devices that support Bluetooth, such as heart-rate monitors, blood meters, thermometers, scales, and so on. For a list of supported devices and their corresponding device data specialization codes, see [Bluetooth's HDP\n Device Data\n Specializations](https://www.bluetooth.com/specifications/assigned-numbers/health-device-profile). These values are also referenced in the ISO/IEEE 11073-20601 \\[7\\] specification as `MDC_DEV_SPEC_PROFILE_*` in the Nomenclature Codes Annex. For more information about HDP, see [Health Device Profile](#health-profile).\n\nHere are the basic steps for working with a profile:\n\n1. Get the default adapter, as described in [Bluetooth setup](/develop/connectivity/bluetooth/setup).\n2. Set up a [`BluetoothProfile.ServiceListener`](/reference/android/bluetooth/BluetoothProfile.ServiceListener). This listener notifies [`BluetoothProfile`](/reference/android/bluetooth/BluetoothProfile) clients when they have been connected to or disconnected from the service.\n3. Use [`getProfileProxy()`](/reference/android/bluetooth/BluetoothAdapter#getProfileProxy(android.content.Context,%20android.bluetooth.BluetoothProfile.ServiceListener,%20int)) to establish a connection to the profile proxy object associated with the profile. In the following example, the profile proxy object is an instance of `BluetoothHeadset`.\n4. In [`onServiceConnected()`](/reference/android/bluetooth/BluetoothProfile.ServiceListener#onServiceConnected(int,%20android.bluetooth.BluetoothProfile)), get a handle to the profile proxy object.\n5. Once you have the profile proxy object, use it to monitor the state of the connection and perform other operations that are relevant to that profile.\n\nThe following code snippet shows how to connect to a `BluetoothHeadset` proxy\nobject so that you can control the Headset profile: \n\n### Kotlin\n\n```kotlin\nvar bluetoothHeadset: BluetoothHeadset? = null\n\n// Get the default adapter\nval bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()\n\nprivate val profileListener = object : BluetoothProfile.ServiceListener {\n\n override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {\n if (profile == BluetoothProfile.HEADSET) {\n bluetoothHeadset = proxy as BluetoothHeadset\n }\n }\n\n override fun onServiceDisconnected(profile: Int) {\n if (profile == BluetoothProfile.HEADSET) {\n bluetoothHeadset = null\n }\n }\n}\n\n// Establish connection to the proxy.\nbluetoothAdapter?.getProfileProxy(context, profileListener, BluetoothProfile.HEADSET)\n\n// ... call functions on bluetoothHeadset\n\n// Close proxy connection after use.\nbluetoothAdapter?.closeProfileProxy(BluetoothProfile.HEADSET, bluetoothHeadset)\n```\n\n### Java\n\n```java\nBluetoothHeadset bluetoothHeadset;\n\n// Get the default adapter\nBluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();\n\nprivate BluetoothProfile.ServiceListener profileListener = new BluetoothProfile.ServiceListener() {\n public void onServiceConnected(int profile, BluetoothProfile proxy) {\n if (profile == BluetoothProfile.HEADSET) {\n bluetoothHeadset = (BluetoothHeadset) proxy;\n }\n }\n public void onServiceDisconnected(int profile) {\n if (profile == BluetoothProfile.HEADSET) {\n bluetoothHeadset = null;\n }\n }\n};\n\n// Establish connection to the proxy.\nbluetoothAdapter.getProfileProxy(context, profileListener, BluetoothProfile.HEADSET);\n\n// ... call functions on bluetoothHeadset\n\n// Close proxy connection after use.\nbluetoothAdapter.closeProfileProxy(bluetoothHeadset);\n```\n\n### Vendor-specific AT commands\n\nApps can register to receive system broadcasts of predefined vendor-specific AT\ncommands sent by headsets (such as a Plantronics +XEVENT command). For example,\nan app could receive broadcasts that indicate a connected device's battery level\nand could notify the user or take other action as needed. Create a broadcast\nreceiver for the\n[`ACTION_VENDOR_SPECIFIC_HEADSET_EVENT`](/reference/android/bluetooth/BluetoothHeadset#ACTION_VENDOR_SPECIFIC_HEADSET_EVENT)\nintent to handle vendor-specific AT commands for the headset.\n\nHealth Device Profile\n---------------------\n\nAndroid supports the Bluetooth Health Device Profile (HDP). The Bluetooth Health\nAPI includes the classes\n[`BluetoothHealth`](/reference/android/bluetooth/BluetoothHealth),\n[`BluetoothHealthCallback`](/reference/android/bluetooth/BluetoothHealthCallback),\nand\n[`BluetoothHealthAppConfiguration`](/reference/android/bluetooth/BluetoothHealthAppConfiguration),\nwhich are described in [Key classes and\ninterfaces](/develop/connectivity/bluetooth#key-classes).\n| **Caution:** The Health Device Profile (HDP) and MCAP protocols are no longer used. New apps should use Bluetooth Low Energy based solutions such as [`BluetoothGatt`](/reference/android/bluetooth/BluetoothGatt), [`BluetoothAdapter.listenUsingL2capChannel()`](/reference/android/bluetooth/BluetoothAdapter#listenUsingL2capChannel()), or [`BluetoothDevice#createL2capChannel(int)`](/reference/android/bluetooth/BluetoothDevice#createL2capChannel(int)).\n\nWhen using the Bluetooth Health API, it's helpful to understand these key HDP\nconcepts:\n\nSource\n: A health device, such as a weight scale, glucose meter, or thermometer, which\n transmits medical data to a smart device, such as an Android phone or tablet.\n\nSink\n: The smart device that receives the medical data. In an HDP app, the\n sink is represented by a `BluetoothHealthAppConfiguration` object.\n\nRegistration\n: The process used to register a sink for communicating with a particular health\n device.\n\nConnection\n: The process used to open a channel between a health device (source) and a\n smart device (sink).\n\n### Create an HDP app\n\nHere are the basic steps involved in creating an HDP app:\n\n1. Get a reference to the `BluetoothHealth` proxy object. As with regular\n headset and A2DP profile devices, you must call `getProfileProxy()` with a\n `BluetoothProfile.ServiceListener` and the\n [`HEALTH`](/reference/android/bluetooth/BluetoothProfile#HEALTH) profile type\n to establish a connection with the profile proxy object.\n\n2. Create a `BluetoothHealthCallback` and register an app configuration\n (`BluetoothHealthAppConfiguration`) that acts as a health sink.\n\n3. Establish a connection to a health device.\n\n | **Note:** Some devices initiate the connection automatically. It is unnecessary to carry out this step for those devices.\n4. When connected successfully to a health device, read and write to the health\n device using the file descriptor. The received data needs to be interpreted\n using a health manager, which implements the [IEEE 11073\n specifications](https://standards.ieee.org/standard/11073-10207-2017.html).\n\n5. When done, close the health channel and unregister the app. The channel also\n closes when there is extended inactivity."]]