Publicité Bluetooth à basse consommation

Le Bluetooth à basse consommation (BLE) économise de l'énergie en restant en mode veille la plupart du temps. Il ne s'active que pour diffuser des annonces et établir des connexions courtes. Les annonces ont donc une incidence à la fois sur la consommation d'énergie et sur la bande passante de transfert de données.

Extension publicitaire Bluetooth 5

Android 8.0 est compatible avec le Bluetooth 5, qui offre des améliorations de diffusion et une publicité de données flexible pour le BLE. Le Bluetooth 5 est compatible avec les couches physiques (PHY) BLE qui conservent la consommation d'énergie réduite du Bluetooth 4.2 et permettent aux utilisateurs de choisir d'augmenter la bande passante ou la portée. Pour en savoir plus, consultez les Spécifications principales de la version 5 de Bluetooth.

Implémentation

Les nouvelles fonctionnalités Bluetooth 5 sont automatiquement disponibles pour les appareils exécutant Android 8.0 avec des contrôleurs Bluetooth compatibles. Utilisez ces méthodes BluetoothAdapter pour vérifier si un appareil est compatible avec les fonctionnalités Bluetooth 5:

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

Pour désactiver les fonctionnalités de publicité, contactez le fournisseur de la puce Bluetooth pour désactiver la prise en charge du chipset.

Les PHY Bluetooth sont exclusifs les uns des autres, et le comportement de chaque PHY est prédéfini par le Bluetooth SIG. Par défaut, Android 8.0 utilise la PHY Bluetooth LE 1M, à partir de Bluetooth 4.2. Le package android.bluetooth.le expose les fonctionnalités publicitaires Bluetooth 5 via les API suivantes:

  • AdvertisingSet
  • AdvertisingSetCallback
  • AdvertisingSetParameters
  • PeriodicAdvertisingParameters

Créez un AdvertisingSet pour modifier les paramètres des annonces Bluetooth à l'aide de la méthode startAdvertisingSet() dans android.bluetooth.le.BluetoothLeAdvertiser. Même si la compatibilité avec le Bluetooth 5 ou ses fonctionnalités de publicité est désactivée, les fonctionnalités de l'API peuvent également s'appliquer au PHY LE 1M.

Exemples

Cet exemple d'application utilise la couche physique Bluetooth LE 1M pour la publicité:

  // 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);
}

Cet exemple d'application utilise la couche physique BLE 2M pour la publicité. L'application vérifie d'abord que l'appareil est compatible avec les fonctionnalités utilisées. Si les fonctionnalités publicitaires sont compatibles, l'application configure le PHY BLE 2M comme PHY principal. Lorsque la PHY 2M est active, la publicité n'est pas compatible avec les contrôleurs Bluetooth 4.x. setLegacyMode est donc défini sur false. Cet exemple modifie les paramètres pendant la diffusion de l'annonce et met également l'annonce en veille.

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);
}

Validation

Exécutez les tests de produits Bluetooth applicables pour vérifier la compatibilité de l'appareil avec Bluetooth 5.