目录

Advertising Development

Overview

Bluetooth advertising and scanning provide APIs for starting and stopping Bluetooth advertising and scanning. Devices can discover nearby Bluetooth devices through advertising and scanning, enabling low-power communication.

When to Use

The main scenarios include enabling and disabling advertising, and enabling and disabling scanning.

Available APIs

For details about the complete API description and sample code, see @ohos.bluetooth.ble (Bluetooth BLE Module).

Name Description
startAdvertising Starts BLE advertising.
stopAdvertising Stops BLE advertising.
startBLEScan Starts BLE scanning.
stopBLEScan Stops BLE scanning.
on('BLEDeviceFind') Subscribes to BLE device discovery events. This API uses an asynchronous callback to return the result.
off('BLEDeviceFind') Unsubscribes from BLE device discovery events.

How to Develop

Import the ble module. Add the ohos.permission.ACCESS_BLUETOOTH permission to the module.json5 file and call requestPermissionsFromUser to obtain user authorization for the ohos.permission.ACCESS_BLUETOOTH permission.

import { ble } from '@kit.ConnectivityKit';
import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
import {abilityAccessCtrl, Context, PermissionRequestResult } from '@kit.AbilityKit';

requestPermissionsFromUser() {
  let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
  try {
    let context = this.getUIContext().getHostContext();
    atManager.requestPermissionsFromUser(context, ['ohos.permission.ACCESS_BLUETOOTH']).then(() => {
    })
  } catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
  }
}

Import the ble module and request the ohos.permission.ACCESS_BLUETOOTH permission. Start BLE advertising. The peer device scans the advertisement. Then, stop BLE advertising.

import { ble } from '@kit.ConnectivityKit';
const TAG: string = 'BleAdvertisingManager';

export class BleAdvertisingManager {
  public async startAdvertising() {
    let manufactureValueBuffer = new Uint8Array(4);
    manufactureValueBuffer[0] = 1;
    manufactureValueBuffer[1] = 2;
    manufactureValueBuffer[2] = 3;
    manufactureValueBuffer[3] = 4;

    let serviceValueBuffer = new Uint8Array(4);
    serviceValueBuffer[0] = 4;
    serviceValueBuffer[1] = 6;
    serviceValueBuffer[2] = 7;
    serviceValueBuffer[3] = 8;
    console.info(`manufactureValueBuffer = ${JSON.stringify(manufactureValueBuffer)}`);
    console.info(`serviceValueBuffer = ${JSON.stringify(serviceValueBuffer)}`);
    try {
      let setting: ble.AdvertiseSetting = {
        interval: 150,
        txPower: 0,
        connectable: true,
      };
      let manufactureDataUnit: ble.ManufactureData = {
        manufactureId: 4567,
        manufactureValue: manufactureValueBuffer.buffer
      };
      let serviceDataUnit: ble.ServiceData = {
        serviceUuid: "00001888-0000-1000-8000-00805f9b34fb",
        serviceValue: serviceValueBuffer.buffer
      };
      let advData: ble.AdvertiseData = {
        serviceUuids: ["00001888-0000-1000-8000-00805f9b34fb"],
        manufactureData: [manufactureDataUnit],
        serviceData: [serviceDataUnit],
      };
      let advResponse: ble.AdvertiseData = {
        serviceUuids: ["00001888-0000-1000-8000-00805f9b34fb"],
        manufactureData: [manufactureDataUnit],
        serviceData: [serviceDataUnit],
      };
      ble.startAdvertising(setting, advData, advResponse);
    } catch (err) {
      console.error(`errCode: ${err.code}, errMessage: ${err.message}`);
    }
  }

  // Stop Bluetooth advertising and release related resources.
  public async stopAdvertising() {
    try {
      ble.stopAdvertising();
    } catch (err) {
      console.error(`errCode: ${err.code}, errMessage: ${err.message}`);
    }
  }
}

let bleAdvertisingManager = new BleAdvertisingManager();

export default bleAdvertisingManager as BleAdvertisingManager;

Start BLE scanning, stop BLE scanning, and discover devices.

import { ble } from '@kit.ConnectivityKit';
const TAG: string = 'BleScanManager';

export class BleScanManager {
  // 1. Subscribe to the scanning result.
  public onScanResult() {
    ble.on('BLEDeviceFind', (data: Array<ble.ScanResult>) => {
      if (data.length > 0) {
        console.info(TAG, `BLE scan result = ${data[0].deviceId}`);
      }
    });
  }

  // 2. Start scanning.
  public startScan() {
    // 2.1 Construct a scan filter that matches the expected advertising packet content.
    let manufactureId = 4567;
    let manufactureData: Uint8Array = new Uint8Array([1, 2, 3, 4]);
    let manufactureDataMask: Uint8Array = new Uint8Array([0xFF, 0xFF, 0xFF, 0xFF]);
    let scanFilter: ble.ScanFilter = {// Define the ScanFilter instance based on service requirements.
      manufactureId: manufactureId,
      manufactureData: manufactureData.buffer,
      manufactureDataMask: manufactureDataMask.buffer
    };

    // 2.2 Construct scanning parameters.
    let scanOptions: ble.ScanOptions = {
      interval: 0,
      dutyMode: ble.ScanDuty.SCAN_MODE_LOW_POWER,
      matchMode: ble.MatchMode.MATCH_MODE_AGGRESSIVE
    }
    try {
      this.onScanResult () // Subscribe to the scanning result.
      ble.startBLEScan([scanFilter], scanOptions);
      console.info(TAG, 'startBleScan success');
    } catch (err) {
      console.error(`errCode: ${err.code}, errMessage: ${err.message}`);
    }
  }

  // 3. Stop scanning.
  public stopScan() {
    try {
      ble.off('BLEDeviceFind', (data: Array<ble.ScanResult>) => { // Unsubscribe from the scanning result.
        console.info(TAG, 'off success');
      });
      ble.stopBLEScan();
      console.info(TAG, 'stopBleScan success');
    } catch (err) {
      console.error(`errCode: ${err.code}, errMessage: ${err.message}`);
    }
  }
}

let bleScanManager = new BleScanManager();
export default bleScanManager as BleScanManager;