Reklamowanie za pomocą Bluetooth Low Energy

Bluetooth Low Energy (BLE) oszczędza energię, ponieważ przez większość czasu pozostaje w trybie uśpienia. Włącza się tylko w celu wyświetlania reklam i nawiązywania krótkich połączeń, więc reklamy mają wpływ zarówno na zużycie energii, jak i na przepustowość transmisji danych.

Rozszerzenie reklamowe Bluetooth 5

Android 8.0 obsługuje Bluetooth 5, który zapewnia lepsze przesyłanie i elastyczne reklamowanie danych w przypadku BLE. Bluetooth 5 obsługuje warstwy fizyczne BLE (PHY), które zachowują zmniejszone zużycie energii Bluetootha 4.2 i umożliwiają użytkownikom wybór większej przepustowości lub zasięgu. Więcej informacji znajdziesz w specyfikacji Bluetooth 5 Core.

Implementacja

Nowe funkcje Bluetootha 5 są automatycznie dostępne na urządzeniach z Androidem 8.0 i zgodnymi kontrolerami Bluetooth. Aby sprawdzić, czy urządzenie obsługuje funkcje Bluetooth 5, skorzystaj z tych BluetoothAdaptermetod:

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

Aby wyłączyć funkcje reklamowe, skontaktuj się z dostawcą układu Bluetooth i poproś o wyłączenie obsługi tego układu.

Warstwy PHY Bluetootha są od siebie niezależne, a ich działanie jest zdefiniowane przez organizację Bluetooth SIG. Domyślnie Android 8.0 używa Bluetooth LE 1M PHY z Bluetooth 4.2. Pakiet android.bluetooth.le udostępnia funkcje reklamowe Bluetooth 5 za pomocą tych interfejsów API:

  • AdvertisingSet
  • AdvertisingSetCallback
  • AdvertisingSetParameters
  • PeriodicAdvertisingParameters

Utwórz AdvertisingSet, aby zmodyfikować ustawienia reklam Bluetootha za pomocą metody startAdvertisingSet()android.bluetooth.le.BluetoothLeAdvertiser. Nawet jeśli obsługa Bluetooth 5 lub jego funkcji reklamowych jest wyłączona, funkcje interfejsu API mogą być też stosowane w przypadku LE 1M PHY.

Przykłady

Ta przykładowa aplikacja używa do reklamowania Bluetooth LE 1M PHY:

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

Ta przykładowa aplikacja używa warstwy fizycznej BLE 2M do reklamowania. Aplikacja najpierw sprawdza, czy urządzenie obsługuje używane funkcje. Jeśli funkcje reklamowe są obsługiwane, aplikacja konfiguruje BLE 2M PHY jako podstawowy PHY. Gdy aktywny jest interfejs 2M PHY, reklama nie obsługuje kontrolerów Bluetooth 4.x, więc wartość setLegacyMode jest ustawiona na false. W tym przykładzie parametry są modyfikowane podczas wyświetlania reklamy, a reklama jest wstrzymywana.

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 can 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 - for example, 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);
}

Weryfikacja

Przeprowadź odpowiednie testy produktów Bluetooth, aby sprawdzić zgodność urządzenia z Bluetoothem 5.