Publicidad Bluetooth de bajo consumo

Bluetooth Low Energy (BLE) conserva energía al permanecer en modo de suspensión la mayor parte del tiempo. Se activa solo para hacer anuncios y conexiones cortas, por lo que los anuncios afectan tanto el consumo de energía como el ancho de banda de transferencia de datos.

Extensión de publicidad Bluetooth 5

Android 8.0 es compatible con Bluetooth 5, que proporciona mejoras de transmisión y anuncios de datos flexibles para BLE. Bluetooth 5 admite capas físicas BLE (PHY) que retienen el consumo de energía reducido de Bluetooth 4.2 y permiten a los usuarios elegir un mayor ancho de banda o alcance. Puede encontrar más información en las especificaciones de Bluetooth 5 Core .

Implementación

Las nuevas funciones de Bluetooth 5 están disponibles automáticamente para dispositivos que ejecutan Android 8.0 con controladores Bluetooth compatibles. Utilice estos métodos de BluetoothAdapter para comprobar si un dispositivo es compatible con las funciones de Bluetooth 5:

  • isLe2MPhySupported()
  • isLeCodedPhySupported()
  • isLeExtendedAdvertisingSupported()
  • isLePeriodicAdvertisingSupported()

Para deshabilitar las funciones publicitarias, trabaje con el proveedor del chip Bluetooth para deshabilitar la compatibilidad con el conjunto de chips.

Los PHY de Bluetooth son exclusivos entre sí, y el comportamiento de cada PHY está predefinido por el SIG de Bluetooth. De manera predeterminada, Android 8.0 usa Bluetooth LE 1M PHY, desde Bluetooth 4.2. El paquete android.bluetooth.le expone las características publicitarias de Bluetooth 5 a través de estas API:

  • AdvertisingSet
  • AdvertisingSetCallback
  • AdvertisingSetParameters
  • PeriodicAdvertisingParameters

Cree un AdvertisingSet para modificar la configuración de anuncios de Bluetooth mediante el método startAdvertisingSet() en android.bluetooth.le.BluetoothLeAdvertiser . Incluso si la compatibilidad con Bluetooth 5 o sus funciones publicitarias está deshabilitada, las funciones API también pueden aplicarse a LE 1M PHY.

Ejemplos

Esta aplicación de ejemplo utiliza Bluetooth LE 1M PHY para publicidad:

  // Start legacy advertising. Works for devices with 5.x controllers,
  and devices that support multi-advertising.

  void example1() {
   BluetoothLeAdvertiser advertiser =
      BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();

   AdvertisingSetParameters parameters = (new AdvertisingSetParameters.Builder())
           .setLegacyMode(true) // True by default, but set here as a reminder.
           .setConnectable(true)
           .setInterval(AdvertisingSetParameters.INTERVAL_HIGH)
           .setTxPowerLevel(AdvertisingSetParameters.TX_POWER_MEDIUM)
           .build();

   AdvertiseData data = (new AdvertiseData.Builder()).setIncludeDeviceName(true).build();

   AdvertisingSetCallback callback = new AdvertisingSetCallback() {
       @Override
       public void onAdvertisingSetStarted(AdvertisingSet advertisingSet, int txPower, int status) {
           Log.i(LOG_TAG, "onAdvertisingSetStarted(): txPower:" + txPower + " , status: "
             + status);
           currentAdvertisingSet = advertisingSet;
       }

       @Override
       public void onAdvertisingDataSet(AdvertisingSet advertisingSet, int status) {
           Log.i(LOG_TAG, "onAdvertisingDataSet() :status:" + status);
       }

       @Override
       public void onScanResponseDataSet(AdvertisingSet advertisingSet, int status) {
           Log.i(LOG_TAG, "onScanResponseDataSet(): status:" + status);
       }

       @Override
       public void onAdvertisingSetStopped(AdvertisingSet advertisingSet) {
           Log.i(LOG_TAG, "onAdvertisingSetStopped():");
       }
   };

   advertiser.startAdvertisingSet(parameters, data, null, null, null, callback);

   // After onAdvertisingSetStarted callback is called, you can modify the
   // advertising data and scan response data:
   currentAdvertisingSet.setAdvertisingData(new AdvertiseData.Builder().
     setIncludeDeviceName(true).setIncludeTxPowerLevel(true).build());
   // Wait for onAdvertisingDataSet callback...
   currentAdvertisingSet.setScanResponseData(new
     AdvertiseData.Builder().addServiceUuid(new ParcelUuid(UUID.randomUUID())).build());
   // Wait for onScanResponseDataSet callback...

   // When done with the advertising:
   advertiser.stopAdvertisingSet(callback);
}

Esta aplicación de ejemplo utiliza BLE 2M PHY para publicidad. La aplicación primero verifica que el dispositivo sea compatible con las funciones que se están utilizando. Si se admiten las funciones publicitarias, la aplicación configura BLE 2M PHY como PHY principal. Mientras 2M PHY está activo, la publicidad no es compatible con los controladores Bluetooth 4.x, por lo que setLegacyMode se establece en false . Este ejemplo modifica los parámetros durante la publicidad y también pausa el anuncio.

void example2() {
   BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
   BluetoothLeAdvertiser advertiser =
     BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();

   // Check if all features are supported
   if (!adapter.isLe2MPhySupported()) {
       Log.e(LOG_TAG, "2M PHY not supported!");
       return;
   }
   if (!adapter.isLeExtendedAdvertisingSupported()) {
       Log.e(LOG_TAG, "LE Extended Advertising not supported!");
       return;
   }

   int maxDataLength = adapter.getLeMaximumAdvertisingDataLength();

   AdvertisingSetParameters.Builder parameters = (new AdvertisingSetParameters.Builder())
           .setLegacyMode(false)
           .setInterval(AdvertisingSetParameters.INTERVAL_HIGH)
           .setTxPowerLevel(AdvertisingSetParameters.TX_POWER_MEDIUM)
           .setPrimaryPhy(BluetoothDevice.PHY_LE_1M)
           .setSecondaryPhy(BluetoothDevice.PHY_LE_2M);

   AdvertiseData data = (new AdvertiseData.Builder()).addServiceData(new
     ParcelUuid(UUID.randomUUID()),
           "You should be able to fit large amounts of data up to maxDataLength. This goes
           up to 1650 bytes. For legacy advertising this would not
           work".getBytes()).build();

   AdvertisingSetCallback callback = new AdvertisingSetCallback() {
       @Override
       public void onAdvertisingSetStarted(AdvertisingSet advertisingSet, int txPower, int status) {
           Log.i(LOG_TAG, "onAdvertisingSetStarted(): txPower:" + txPower + " , status: "
            + status);
           currentAdvertisingSet = advertisingSet;
       }

       @Override
       public void onAdvertisingSetStopped(AdvertisingSet advertisingSet) {
           Log.i(LOG_TAG, "onAdvertisingSetStopped():");
       }
   };

   advertiser.startAdvertisingSet(parameters.build(), data, null, null, null, callback);

   // After the set starts, you can modify the data and parameters of currentAdvertisingSet.
   currentAdvertisingSet.setAdvertisingData((new
     AdvertiseData.Builder()).addServiceData(new ParcelUuid(UUID.randomUUID()),
           "Without disabling the advertiser first, you can set the data, if new data is
            less than 251 bytes long.".getBytes()).build());

   // Wait for onAdvertisingDataSet callback...

   // Can also stop and restart the advertising
   currentAdvertisingSet.enableAdvertising(false, 0, 0);
   // Wait for onAdvertisingEnabled callback...
   currentAdvertisingSet.enableAdvertising(true, 0, 0);
   // Wait for onAdvertisingEnabled callback...

   // Or modify the parameters - i.e. lower the tx power
   currentAdvertisingSet.enableAdvertising(false, 0, 0);
   // Wait for onAdvertisingEnabled callback...
   currentAdvertisingSet.setAdvertisingParameters(parameters.setTxPowerLevel
     (AdvertisingSetParameters.TX_POWER_LOW).build());
   // Wait for onAdvertisingParametersUpdated callback...
   currentAdvertisingSet.enableAdvertising(true, 0, 0);
   // Wait for onAdvertisingEnabled callback...

   // When done with the advertising:
   advertiser.stopAdvertisingSet(callback);
}

Verificación

Ejecute las pruebas de productos Bluetooth correspondientes para verificar la compatibilidad del dispositivo con Bluetooth 5.

AOSP contiene Android Comms Test Suite (ACTS), que incluye pruebas para Bluetooth 5. Las pruebas ACTS para Bluetooth 5 se pueden encontrar en tools/test/connectivity/acts/tests/google/ble/bt5 .