Publicidade Bluetooth de Baixa Energia

O Bluetooth Low Energy (BLE) conserva energia permanecendo no modo de suspensão a maior parte do tempo. Ele acorda apenas para fazer anúncios e conexões curtas, então os anúncios afetam tanto o consumo de energia quanto a largura de banda de transferência de dados.

Extensão de publicidade Bluetooth 5

O Android 8.0 é compatível com Bluetooth 5, que oferece melhorias de transmissão e publicidade de dados flexível para BLE. O Bluetooth 5 suporta BLE Physical Layers (PHYs) que retêm o consumo de energia reduzido do Bluetooth 4.2 e permitem que os usuários escolham maior largura de banda ou alcance. Mais informações podem ser encontradas nas Especificações do Bluetooth 5 Core .

Implementação

Novos recursos do Bluetooth 5 estão disponíveis automaticamente para dispositivos que executam o Android 8.0 com controladores Bluetooth compatíveis. Use estes métodos do BluetoothAdapter para verificar se um dispositivo oferece suporte aos recursos do Bluetooth 5:

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

Para desativar os recursos de publicidade, trabalhe com o fornecedor do chip Bluetooth para desativar o suporte ao conjunto de chips.

Os Bluetooth PHYs são exclusivos uns dos outros, e o comportamento de cada PHY é predefinido pelo Bluetooth SIG. Por padrão, o Android 8.0 usa Bluetooth LE 1M PHY, do Bluetooth 4.2. O pacote android.bluetooth.le expõe os recursos de publicidade do Bluetooth 5 por meio dessas APIs:

  • AdvertisingSet
  • AdvertisingSetCallback
  • AdvertisingSetParameters
  • PeriodicAdvertisingParameters

Crie um AdvertisingSet para modificar as configurações de anúncio Bluetooth usando o método startAdvertisingSet() em android.bluetooth.le.BluetoothLeAdvertiser . Mesmo que o suporte para Bluetooth 5 ou seus recursos de publicidade esteja desativado, os recursos da API também podem ser aplicados ao LE 1M PHY.

Exemplos

Este aplicativo de exemplo usa Bluetooth LE 1M PHY para publicidade:

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

Este aplicativo de exemplo usa o BLE 2M PHY para publicidade. O aplicativo primeiro verifica se o dispositivo é compatível com os recursos que estão sendo usados. Se os recursos de publicidade forem suportados, o aplicativo configurará o BLE 2M PHY como o PHY principal. Enquanto 2M PHY está ativo, o anúncio não suporta controladores Bluetooth 4.x, então setLegacyMode é definido como false . Este exemplo modifica os parâmetros durante a publicidade e também pausa o anúncio.

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

Verificação

Execute testes de produtos Bluetooth aplicáveis ​​para verificar a compatibilidade do dispositivo com o Bluetooth 5.

O AOSP contém o Android Comms Test Suite (ACTS), que inclui testes para Bluetooth 5. Os testes ACTS para Bluetooth 5 podem ser encontrados em tools/test/connectivity/acts/tests/google/ble/bt5 .