harmony 鸿蒙@ohos.bluetooth (Bluetooth)

2022-08-09 浏览 (1403)

@ohos.bluetooth (Bluetooth)

The Bluetooth module provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising.

NOTE

  • The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
  • The APIs provided by this module are no longer maintained since API version 9. You are advised to use profile APIs of @ohos.bluetooth.ble.

Modules to Import

import bluetooth from '@ohos.bluetooth';

bluetooth.enableBluetooth8+(deprecated)

enableBluetooth(): boolean

Enables Bluetooth.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.enableBluetooth.

Required permissions: ohos.permission.DISCOVER_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
booleanReturns true if Bluetooth is enabled; returns false otherwise.

Example

let enable : boolean = bluetooth.enableBluetooth();

bluetooth.disableBluetooth8+(deprecated)

disableBluetooth(): boolean

Disables Bluetooth.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.disableBluetooth.

Required permissions: ohos.permission.DISCOVER_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
booleanReturns true if Bluetooth is disabled; returns false otherwise.

Example

let disable : boolean = bluetooth.disableBluetooth();

bluetooth.getLocalName8+(deprecated)

getLocalName(): string

Obtains the name of the local Bluetooth device.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.getLocalName.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
stringName of the local Bluetooth device obtained.

Example

let localName : string = bluetooth.getLocalName();

bluetooth.getState(deprecated)

getState(): BluetoothState

Obtains the Bluetooth state.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.getState.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
BluetoothStateBluetooth state obtained.

Example

let state : bluetooth.BluetoothState = bluetooth.getState();

bluetooth.getBtConnectionState(deprecated)

getBtConnectionState(): ProfileConnectionState

Obtains the local profile connection state.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.getBtConnectionState.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
ProfileConnectionStateProfile connection state obtained.

Example

let connectionState : bluetooth.ProfileConnectionState = bluetooth.getBtConnectionState();

bluetooth.setLocalName8+(deprecated)

setLocalName(name: string): boolean

Sets the name of the local Bluetooth device.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.setLocalName.

Required permissions: ohos.permission.DISCOVER_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
namestringYesBluetooth device name to set. It cannot exceed 248 bytes.

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

let ret : boolean = bluetooth.setLocalName('device_name');

bluetooth.pairDevice(deprecated)

pairDevice(deviceId: string): boolean

Initiates Bluetooth pairing.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.pairDevice.

Required permissions: ohos.permission.DISCOVER_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
deviceIdstringYesAddress of the remote device to pair, for example, XX:XX:XX:XX:XX:XX.

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

// The address can be scanned.
let result : boolean = bluetooth.pairDevice("XX:XX:XX:XX:XX:XX");

bluetooth.getProfileConnState8+(deprecated)

getProfileConnState(profileId: ProfileId): ProfileConnectionState

Obtains the connection status of the specified profile.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.getProfileConnectionState.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
ProfileIdprofileIdYesID of the profile to obtain, for example, PROFILE_A2DP_SOURCE.

Return value

TypeDescription
ProfileConnectionStateProfile connection state obtained.

Example

let result : bluetooth.ProfileConnectionState = bluetooth.getProfileConnState(bluetooth.ProfileId.PROFILE_A2DP_SOURCE);

bluetooth.cancelPairedDevice8+(deprecated)

cancelPairedDevice(deviceId: string): boolean

Cancels a paired remote device.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.cancelPairedDevice.

System API: This is a system API.

Required permissions: ohos.permission.DISCOVER_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
deviceIdstringYesAddress of the remote device to cancel, for example, XX:XX:XX:XX:XX:XX.

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

let result : boolean = bluetooth.cancelPairedDevice("XX:XX:XX:XX:XX:XX");

bluetooth.getRemoteDeviceName8+(deprecated)

getRemoteDeviceName(deviceId: string): string

Obtains the name of the remote Bluetooth device.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.getRemoteDeviceName.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
deviceIdstringYesAddress of the target remote device, for example, XX:XX:XX:XX:XX:XX.

Return value

TypeDescription
stringDevice name (a string) obtained.

Example

let remoteDeviceName : string = bluetooth.getRemoteDeviceName("XX:XX:XX:XX:XX:XX");

bluetooth.getRemoteDeviceClass8+(deprecated)

getRemoteDeviceClass(deviceId: string): DeviceClass

Obtains the class of the remote Bluetooth device.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.getRemoteDeviceClass.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
deviceIdstringYesAddress of the target remote device, for example, XX:XX:XX:XX:XX:XX.

Return value

TypeDescription
DeviceClassClass of the remote device obtained.

Example

let remoteDeviceClass : bluetooth.DeviceClass = bluetooth.getRemoteDeviceClass("XX:XX:XX:XX:XX:XX");

bluetooth.getPairedDevices8+(deprecated)

getPairedDevices(): Array<string>

Obtains the paired devices.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.getPairedDevices.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
Array<string>Addresses of the paired Bluetooth devices.

Example

let devices : Array<string> = bluetooth.getPairedDevices();

bluetooth.setBluetoothScanMode8+(deprecated)

setBluetoothScanMode(mode: ScanMode, duration: number): boolean

Sets the Bluetooth scan mode so that the device can be discovered by a remote device.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.setBluetoothScanMode.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
modeScanModeYesBluetooth scan mode to set.
durationnumberYesDuration (in ms) in which the device can be discovered. The value 0 indicates unlimited time.

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

// The device can be discovered and connected only when the discoverable and connectable mode is used.
let result : boolean = bluetooth.setBluetoothScanMode(bluetooth.ScanMode
    .SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 100);

bluetooth.getBluetoothScanMode8+(deprecated)

getBluetoothScanMode(): ScanMode

Obtains the Bluetooth scan mode.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.getBluetoothScanMode.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
ScanModeBluetooth scan mode obtained.

Example

let scanMode : bluetooth.ScanMode = bluetooth.getBluetoothScanMode();

bluetooth.startBluetoothDiscovery8+(deprecated)

startBluetoothDiscovery(): boolean

Starts Bluetooth scan to discover remote devices.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.startBluetoothDiscovery.

Required permissions: ohos.permission.DISCOVER_BLUETOOTH and ohos.permission.LOCATION

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

let deviceId : Array<string>;
function onReceiveEvent(data : Array<string>) {
    deviceId = data;
}
bluetooth.on('bluetoothDeviceFind', onReceiveEvent);
let result : boolean = bluetooth.startBluetoothDiscovery();

bluetooth.stopBluetoothDiscovery8+(deprecated)

stopBluetoothDiscovery(): boolean

Stops Bluetooth scan.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.stopBluetoothDiscovery.

Required permissions: ohos.permission.DISCOVER_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

let result : boolean = bluetooth.stopBluetoothDiscovery();

bluetooth.setDevicePairingConfirmation8+(deprecated)

setDevicePairingConfirmation(device: string, accept: boolean): boolean

Sets the device pairing confirmation.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.setDevicePairingConfirmation.

Required permissions: ohos.permission.MANAGE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
devicestringYesAddress of the remote device, for example, XX:XX:XX:XX:XX:XX.
acceptbooleanYesWhether to accept the pairing request. The value true means to accept the pairing request, and the value false means the opposite.

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

// Subscribe to the pinRequired event and configure the pairing confirmation after receiving a pairing request from the remote device.
function onReceivePinRequiredEvent(data : bluetooth.PinRequiredParam) { // data is the input parameter for the pairing request.
    console.info('pin required  = '+ JSON.stringify(data));
    bluetooth.setDevicePairingConfirmation(data.deviceId, true);
}
bluetooth.on("pinRequired", onReceivePinRequiredEvent);

bluetooth.on('bluetoothDeviceFind')8+(deprecated)

on(type: "bluetoothDeviceFind", callback: Callback<Array<string>>): void

Subscribes to the Bluetooth device discovery events.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.on('bluetoothDeviceFind').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value bluetoothDeviceFind indicates an event reported when a Bluetooth device is discovered.
callbackCallback<Array<string>>YesCallback invoked to return the discovered devices. You need to implement this callback.

Return value

No value is returned.

Example

function onReceiveEvent(data : Array<string>) { // data is an array of Bluetooth device addresses.
    console.info('bluetooth device find = '+ JSON.stringify(data));
}
bluetooth.on('bluetoothDeviceFind', onReceiveEvent);

bluetooth.off('bluetoothDeviceFind')8+(deprecated)

off(type: "bluetoothDeviceFind", callback?: Callback<Array<string>>): void

Unsubscribes from the Bluetooth device discovery events.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.off('bluetoothDeviceFind').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value bluetoothDeviceFind indicates an event reported when a Bluetooth device is discovered.
callbackCallback<Array<string>>NoCallback for the bluetoothDeviceFind event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to type.

Return value

No value is returned.

Example

function onReceiveEvent(data : Array<string>) {
    console.info('bluetooth device find = '+ JSON.stringify(data));
}
bluetooth.on('bluetoothDeviceFind', onReceiveEvent);
bluetooth.off('bluetoothDeviceFind', onReceiveEvent);

bluetooth.on('pinRequired')8+(deprecated)

on(type: "pinRequired", callback: Callback<PinRequiredParam>): void

Subscribes to the pairing request events of the remote Bluetooth device.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.on('pinRequired').

Required permissions: ohos.permission.DISCOVER_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value pinRequired indicates a pairing request event.
callbackCallback<PinRequiredParam>YesCallback invoked to return the pairing request. You need to implement this callback.

Return value

No value is returned.

Example

function onReceiveEvent(data : bluetooth.PinRequiredParam) { // data is the pairing request parameter.
    console.info('pin required = '+ JSON.stringify(data));
}
bluetooth.on('pinRequired', onReceiveEvent);

bluetooth.off('pinRequired')8+(deprecated)

off(type: "pinRequired", callback?: Callback<PinRequiredParam>): void

Unsubscribes from the pairing request events of the remote Bluetooth device.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.off('pinRequired').

Required permissions: ohos.permission.DISCOVER_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value pinRequired indicates a pairing request event.
callbackCallback<PinRequiredParam>NoCallback for the Bluetooth pairing request event. The input parameter is the pairing request parameter. If this parameter is not set, this method unsubscribes from all callbacks corresponding to type.

Return value

No value is returned.

Example

function onReceiveEvent(data : bluetooth.PinRequiredParam) {
    console.info('pin required = '+ JSON.stringify(data));
}
bluetooth.on('pinRequired', onReceiveEvent);
bluetooth.off('pinRequired', onReceiveEvent);

bluetooth.on('bondStateChange')8+(deprecated)

on(type: "bondStateChange", callback: Callback<BondStateParam>): void

Subscribes to the Bluetooth pairing state changes.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.on('bondStateChange').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value bondStateChange indicates a Bluetooth pairing state change event.
callbackCallback<BondStateParam>YesCallback invoked to return the pairing state. You need to implement this callback.

Return value

No value is returned.

Example

function onReceiveEvent(data : bluetooth.BondStateParam) { // data, as the input parameter of the callback, indicates the pairing state.
    console.info('pair state = '+ JSON.stringify(data));
}
bluetooth.on('bondStateChange', onReceiveEvent);

bluetooth.off('bondStateChange')8+(deprecated)

off(type: "bondStateChange", callback?: Callback<BondStateParam>): void

Unsubscribes from the Bluetooth pairing state changes.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.off('bondStateChange').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value bondStateChange indicates a Bluetooth pairing state change event.
callbackCallback<BondStateParam>NoCallback for the change of the Bluetooth pairing state. If this parameter is not set, this method unsubscribes from all callbacks corresponding to type.

Return value

No value is returned.

Example

function onReceiveEvent(data : bluetooth.BondStateParam) {
    console.info('bond state = '+ JSON.stringify(data));
}
bluetooth.on('bondStateChange', onReceiveEvent);
bluetooth.off('bondStateChange', onReceiveEvent);

bluetooth.on('stateChange')8+(deprecated)

on(type: "stateChange", callback: Callback<BluetoothState>): void

Subscribes to the Bluetooth connection state changes.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.on('stateChange').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value stateChange indicates a Bluetooth connection state change event.
callbackCallback<BluetoothState>YesCallback invoked to return the Bluetooth connection state. You need to implement this callback.

Return value

No value is returned.

Example

function onReceiveEvent(data : bluetooth.BluetoothState) {
    console.info('bluetooth state = '+ JSON.stringify(data));
}
bluetooth.on('stateChange', onReceiveEvent);

bluetooth.off('stateChange')8+(deprecated)

off(type: "stateChange", callback?: Callback<BluetoothState>): void

Unsubscribes from the Bluetooth connection state changes.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.off('stateChange').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value stateChange indicates a Bluetooth connection state change event.
callbackCallback<BluetoothState>NoCallback for the Bluetooth connection state change event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to type.

Return value

No value is returned.

Example

function onReceiveEvent(data : bluetooth.BluetoothState) {
    console.info('bluetooth state = '+ JSON.stringify(data));
}
bluetooth.on('stateChange', onReceiveEvent);
bluetooth.off('stateChange', onReceiveEvent);

bluetooth.sppListen8+(deprecated)

sppListen(name: string, option: SppOption, callback: AsyncCallback<number>): void

Creates a server listening socket.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.sppListen.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
namestringYesName of the service.
optionSppOptionYesSerial port profile (SPP) listening configuration.
callbackAsyncCallback<number>YesCallback invoked to return the server socket ID.

Example

import { BusinessError } from '@ohos.base';
let serverNumber = -1;
function serverSocket(code : BusinessError, number : number) {
  console.log('bluetooth error code: ' + code.code);
  if (code.code == 0) {
    console.log('bluetooth serverSocket Number: ' + number);
    serverNumber = number;
  }
}

let sppOption : bluetooth.SppOption = {uuid: '00001810-0000-1000-8000-00805F9B34FB', secure: false, type: 0};
bluetooth.sppListen('server1', sppOption, serverSocket);

bluetooth.sppAccept8+(deprecated)

sppAccept(serverSocket: number, callback: AsyncCallback<number>): void

Listens for a connection to be made to this socket from the client and accepts it.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.sppAccept.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
serverSocketnumberYesServer socket ID.
callbackAsyncCallback<number>YesCallback invoked to return the client socket ID.

Example

import { BusinessError } from '@ohos.base';
let serverNumber = -1;
function serverSocket(code : BusinessError, number : number) {
  console.log('bluetooth error code: ' + code.code);
  if (code.code == 0) {
    console.log('bluetooth serverSocket Number: ' + number);
    serverNumber = number;
  }
}
let clientNumber = -1;
function acceptClientSocket(code : BusinessError, number : number) {
  console.log('bluetooth error code: ' + code.code);
  if (code.code == 0) {
    console.log('bluetooth clientSocket Number: ' + number);
    // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the server.
    clientNumber = number;
  }
}
bluetooth.sppAccept(serverNumber, acceptClientSocket);

bluetooth.sppConnect8+(deprecated)

sppConnect(device: string, option: SppOption, callback: AsyncCallback<number>): void

Initiates an SPP connection to a remote device from the client.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.sppConnect.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
devicestringYesAddress of the remote device, for example, XX:XX:XX:XX:XX:XX.
optionSppOptionYesConfiguration for connecting to the SPP client.
callbackAsyncCallback<number>YesCallback invoked to return the client socket ID.

Example

import { BusinessError } from '@ohos.base';
let clientNumber = -1;
function clientSocket(code : BusinessError, number : number) {
  if (code.code != 0||code == null) {
    return;
  }
  console.log('bluetooth serverSocket Number: ' + number);
  // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client.
  clientNumber = number;
}
let sppOption : bluetooth.SppOption = {uuid: '00001810-0000-1000-8000-00805F9B34FB', secure: false, type: 0};
bluetooth.sppConnect('XX:XX:XX:XX:XX:XX', sppOption, clientSocket);

bluetooth.sppCloseServerSocket8+(deprecated)

sppCloseServerSocket(socket: number): void

Closes the listening socket of the server.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.sppCloseServerSocket.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
socketnumberYesID of the listening socket on the server. The ID is obtained by sppListen.

Example

import { BusinessError } from '@ohos.base';
let serverNumber = -1;
function serverSocket(code : BusinessError, number : number) {
  console.log('bluetooth error code: ' + code.code);
  if (code.code == 0) {
    console.log('bluetooth serverSocket Number: ' + number);
    serverNumber = number;
  }
}
bluetooth.sppCloseServerSocket(serverNumber);

bluetooth.sppCloseClientSocket8+(deprecated)

sppCloseClientSocket(socket: number): void

Closes the client socket.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.sppCloseClientSocket.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
NameTypeMandatoryDescription
socketnumberYesClient socket ID, which is obtained by sppAccept or sppConnect.

Example

import { BusinessError } from '@ohos.base';
let clientNumber = -1;
function clientSocket(code : BusinessError, number : number) {
  if (code.code != 0||code == null) {
    return;
  }
  console.log('bluetooth serverSocket Number: ' + number);
  // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client.
  clientNumber = number;
}
bluetooth.sppCloseClientSocket(clientNumber);

bluetooth.sppWrite8+(deprecated)

sppWrite(clientSocket: number, data: ArrayBuffer): boolean

Writes data to the remote device through the socket.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.sppWrite.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
clientSocketnumberYesClient socket ID, which is obtained by sppAccept or sppConnect.
dataArrayBufferYesData to write.

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

import { BusinessError } from '@ohos.base';
let clientNumber = -1;
function clientSocket(code : BusinessError, number : number) {
  if (code.code != 0||code == null) {
    return;
  }
  console.log('bluetooth serverSocket Number: ' + number);
  // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client.
  clientNumber = number;
}
let arrayBuffer = new ArrayBuffer(8);
let data = new Uint8Array(arrayBuffer);
data[0] = 123;
let ret : boolean = bluetooth.sppWrite(clientNumber, arrayBuffer);
if (ret) {
  console.log('spp write successfully');
} else {
  console.log('spp write failed');
}

bluetooth.on('sppRead')8+(deprecated)

on(type: "sppRead", clientSocket: number, callback: Callback<ArrayBuffer>): void

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.on('sppRead').

Subscribes to the SPP read request events.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value sppRead indicates an SPP read request event.
clientSocketnumberYesClient socket ID, which is obtained by sppAccept or sppConnect.
callbackCallback<ArrayBuffer>YesCallback invoked to return the data read.

Return value

No value is returned.

Example

import { BusinessError } from '@ohos.base';
let clientNumber = -1;
function clientSocket(code : BusinessError, number : number) {
  if (code.code != 0||code == null) {
    return;
  }
  console.log('bluetooth serverSocket Number: ' + number);
  // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client.
  clientNumber = number;
}
function dataRead(dataBuffer : ArrayBuffer) {
  let data = new Uint8Array(dataBuffer);
  console.log('bluetooth data is: ' + data[0]);
}
bluetooth.on('sppRead', clientNumber, dataRead);

bluetooth.off('sppRead')8+(deprecated)

off(type: "sppRead", clientSocket: number, callback?: Callback<ArrayBuffer>): void

Unsubscribes from the SPP read request events.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.off('sppRead').

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value sppRead indicates an SPP read request event.
clientSocketnumberYesClient socket ID, which is obtained by sppAccept or sppConnect.
callbackCallback<ArrayBuffer>NoCallback for the SPP read request event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to type.

Return value

No value is returned.

Example

import { BusinessError } from '@ohos.base';
let clientNumber = -1;
function clientSocket(code : BusinessError, number : number) {
  if (code.code != 0||code == null) {
    return;
  }
  console.log('bluetooth serverSocket Number: ' + number);
  // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client.
  clientNumber = number;
}
bluetooth.off('sppRead', clientNumber);

bluetooth.getProfile8+(deprecated)

getProfile(profileId: ProfileId): A2dpSourceProfile|HandsFreeAudioGatewayProfile

Obtains a profile object.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.getProfileInstance.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
profileIdProfileIdYesID of the profile to obtain, for example, PROFILE_A2DP_SOURCE.

Return value

TypeDescription
A2dpSourceProfile or HandsFreeAudioGatewayProfileProfile object obtained. Only A2dpSourceProfile and HandsFreeAudioGatewayProfile are supported.

Example

let a2dpSrc : bluetooth.A2dpSourceProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile;

bluetooth.BLE

createGattServer(deprecated)

createGattServer(): GattServer

Creates a GattServer instance.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.BLE.createGattServer.

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
GattServerGattServer instance created. Before using a method of the server, you must create a GattSever instance.

Example

let gattServer : bluetooth.GattServer = bluetooth.BLE.createGattServer();

createGattClientDevice(deprecated)

createGattClientDevice(deviceId: string): GattClientDevice

Creates a GattClientDevice instance.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.BLE.createGattClientDevice.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
deviceIdstringYesAddress of the remote device, for example, XX:XX:XX:XX:XX:XX.

Return value

TypeDescription
GattClientDeviceGattClientDevice instance created. Before using a method of the client, you must create a GattClientDevice instance.

Example

let device : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');

getConnectedBLEDevices(deprecated)

getConnectedBLEDevices(): Array<string>

Obtains the BLE devices connected to this device.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.BLE.getConnectedBLEDevices.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
Array<string>Addresses of the BLE devices connected to this device.

Example

let result : Array<string> = bluetooth.BLE.getConnectedBLEDevices();

startBLEScan(deprecated)

startBLEScan(filters: Array<ScanFilter>, options?: ScanOptions): void

Starts a BLE scan.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.BLE.startBLEScan.

Required permissions: ohos.permission.DISCOVER_BLUETOOTH, ohos.permission.MANAGE_BLUETOOTH, and ohos.permission.LOCATION

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
filtersArray<ScanFilter>YesCriteria for filtering the scan result. Set this parameter to null if you do not want to filter the scan result.
optionsScanOptionsNoScan options.

Return value

No value is returned.

Example

function onReceiveEvent(data : Array<bluetooth.ScanResult>) {
    console.info('BLE scan device find result = '+ JSON.stringify(data));
}
bluetooth.BLE.on("BLEDeviceFind", onReceiveEvent);
let scanOptions : bluetooth.ScanOptions = {
    interval: 500,
    dutyMode: bluetooth.ScanDuty.SCAN_MODE_LOW_POWER,
    matchMode: bluetooth.MatchMode.MATCH_MODE_AGGRESSIVE,
}

let scanFilter : bluetooth.ScanFilter = {
    deviceId:"XX:XX:XX:XX:XX:XX",
    name:"test",
    serviceUuid:"00001888-0000-1000-8000-00805f9b34fb"
}
bluetooth.BLE.startBLEScan(
    [scanFilter], scanOptions
);

stopBLEScan(deprecated)

stopBLEScan(): void

Stops the BLE scan.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.BLE.stopBLEScan.

Required permissions: ohos.permission.DISCOVER_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

No value is returned.

Example

bluetooth.BLE.stopBLEScan();

on('BLEDeviceFind')(deprecated)

on(type: "BLEDeviceFind", callback: Callback<Array<ScanResult>>): void

Subscribe to the BLE device discovery events.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.BLE.on('BLEDeviceFind').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value BLEDeviceFind indicates an event reported when a BLE device is discovered.
callbackCallback<Array<ScanResult>>YesCallback invoked to return the discovered devices. You need to implement this callback.

Return value

No value is returned.

Example

function onReceiveEvent(data : Array<bluetooth.ScanResult>) {
    console.info('bluetooth device find = '+ JSON.stringify(data));
}
bluetooth.BLE.on('BLEDeviceFind', onReceiveEvent);

off('BLEDeviceFind')(deprecated)

off(type: "BLEDeviceFind", callback?: Callback<Array<ScanResult>>): void

Unsubscribes from the BLE device discovery events.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.BLE.off('BLEDeviceFind').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value BLEDeviceFind indicates an event reported when a BLE device is discovered.
callbackCallback<Array<ScanResult>>NoCallback for the BLEDeviceFind event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to type.

Return value

No value is returned.

Example

function onReceiveEvent(data : Array<bluetooth.ScanResult>) {
    console.info('bluetooth device find = '+ JSON.stringify(data));
}
bluetooth.BLE.on('BLEDeviceFind', onReceiveEvent);
bluetooth.BLE.off('BLEDeviceFind', onReceiveEvent);

BaseProfile

Provides the profile base class.

getConnectionDevices8+(deprecated)

getConnectionDevices(): Array<string>

Obtains the connected devices.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.BaseProfile.getConnectionDevices.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
Array<string>Addresses of the connected devices.

Example

let a2dpSrc : bluetooth.A2dpSourceProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile;
let retArray : Array<string> = a2dpSrc.getConnectionDevices();

getDeviceState8+(deprecated)

getDeviceState(device: string): ProfileConnectionState

Obtains the connection state of the profile.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.BaseProfile.getDeviceState.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
devicestringYesAddress of the target device.

Return value

TypeDescription
ProfileConnectionStateProfile connection state obtained.

Example

let a2dpSrc : bluetooth.A2dpSourceProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile;
let ret : bluetooth.ProfileConnectionState = a2dpSrc.getDeviceState('XX:XX:XX:XX:XX:XX');

A2dpSourceProfile

Before using a method of A2dpSourceProfile, you need to create an instance of this class by using the getProfile() method.

connect8+(deprecated)

connect(device: string): boolean

Sets up an Advanced Audio Distribution Profile (A2DP) connection.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.A2dpSourceProfile.connect.

Required permissions: ohos.permission.DISCOVER_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
devicestringYesAddress of the target device.

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

let a2dpSrc : bluetooth.A2dpSourceProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile;
let ret : boolean = a2dpSrc.connect('XX:XX:XX:XX:XX:XX');

disconnect8+(deprecated)

disconnect(device: string): boolean

Disconnects an A2DP connection.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.A2dpSourceProfile.disconnect.

Required permissions: ohos.permission.DISCOVER_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
devicestringYesAddress of the target device.

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

let a2dpSrc : bluetooth.A2dpSourceProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile;
let ret : boolean = a2dpSrc.disconnect('XX:XX:XX:XX:XX:XX');

on('connectionStateChange')8+(deprecated)

on(type: "connectionStateChange", callback: Callback<StateChangeParam>): void

Subscribes to the A2DP connection state changes.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.A2dpSourceProfile.on('connectionStateChange').

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value connectionStateChange indicates an A2DP connection state change event.
callbackCallback<StateChangeParam>YesCallback invoked to return the A2DP connection state change event.

Return value

No value is returned.

Example

function onReceiveEvent(data : bluetooth.StateChangeParam) {
    console.info('a2dp state = '+ JSON.stringify(data));
}
let a2dpSrc : bluetooth.A2dpSourceProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile;
a2dpSrc.on('connectionStateChange', onReceiveEvent);

off('connectionStateChange')8+(deprecated)

off(type: "connectionStateChange", callback?: Callback<StateChangeParam>): void

Unsubscribes from the A2DP connection state changes.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.A2dpSourceProfile.off('connectionStateChange').

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value connectionStateChange indicates an A2DP connection state change event.
callbackCallback<StateChangeParam>NoCallback for the A2DP connection state change event.

Return value

No value is returned.

Example

function onReceiveEvent(data : bluetooth.StateChangeParam) {
    console.info('a2dp state = '+ JSON.stringify(data));
}
let a2dpSrc : bluetooth.A2dpSourceProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile;
a2dpSrc.on('connectionStateChange', onReceiveEvent);
a2dpSrc.off('connectionStateChange', onReceiveEvent);

getPlayingState8+(deprecated)

getPlayingState(device: string): PlayingState

Obtains the playing state of a device.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.A2dpSourceProfile.getPlayingState.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
devicestringYesAddress of the target device.

Return value

TypeDescription
PlayingStatePlaying state of the remote device obtained.

Example

let a2dpSrc : bluetooth.A2dpSourceProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile;
let state : bluetooth.PlayingState = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX');

HandsFreeAudioGatewayProfile

Before using a method of HandsFreeAudioGatewayProfile, you need to create an instance of this class by using the getProfile() method.

connect8+(deprecated)

connect(device: string): boolean

Sets up a Hands-free Profile (HFP) connection of a device.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.HandsFreeAudioGatewayProfile.connect.

Required permissions: ohos.permission.DISCOVER_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
devicestringYesAddress of the target device.

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

let hfpAg : bluetooth.HandsFreeAudioGatewayProfile= bluetooth.getProfile(bluetooth.ProfileId
    .PROFILE_HANDS_FREE_AUDIO_GATEWAY);
let ret : boolean = hfpAg.connect('XX:XX:XX:XX:XX:XX');

disconnect8+(deprecated)

disconnect(device: string): boolean

Disconnects the HFP connection of a device.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.HandsFreeAudioGatewayProfile.disconnect.

Required permissions: ohos.permission.DISCOVER_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
devicestringYesAddress of the target device.

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

let hfpAg : bluetooth.HandsFreeAudioGatewayProfile = bluetooth.getProfile(bluetooth.ProfileId
    .PROFILE_HANDS_FREE_AUDIO_GATEWAY);
let ret : boolean = hfpAg.disconnect('XX:XX:XX:XX:XX:XX');

on('connectionStateChange')8+(deprecated)

on(type: "connectionStateChange", callback: Callback<StateChangeParam>): void

Subscribes to the HFP connection state changes.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.HandsFreeAudioGatewayProfile.on('connectionStateChange').

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value connectionStateChange indicates an HFP connection state change event.
callbackCallback<StateChangeParam>YesCallback invoked to return the HFP connection state change event.

Return value

No value is returned.

Example

function onReceiveEvent(data : bluetooth.StateChangeParam) {
    console.info('hfp state = '+ JSON.stringify(data));
}
let hfpAg : bluetooth.HandsFreeAudioGatewayProfile= bluetooth.getProfile(bluetooth.ProfileId
    .PROFILE_HANDS_FREE_AUDIO_GATEWAY);
hfpAg.on('connectionStateChange', onReceiveEvent);

off('connectionStateChange')8+(deprecated)

off(type: "connectionStateChange", callback?: Callback<StateChangeParam>): void

Unsubscribes from the HFP connection state changes.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.HandsFreeAudioGatewayProfile.off('connectionStateChange').

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value connectionStateChange indicates an HFP connection state change event.
callbackCallback<StateChangeParam>NoCallback for the HFP connection state change event.

Return value

No value is returned.

Example

function onReceiveEvent(data : bluetooth.StateChangeParam) {
    console.info('hfp state = '+ JSON.stringify(data));
}
let hfpAg : bluetooth.HandsFreeAudioGatewayProfile= bluetooth.getProfile(bluetooth.ProfileId
    .PROFILE_HANDS_FREE_AUDIO_GATEWAY);
hfpAg.on('connectionStateChange', onReceiveEvent);
hfpAg.off('connectionStateChange', onReceiveEvent);

GattServer

Implements the Generic Attribute Profile (GATT) server. Before using a method of this class, you need to create a GattServer instance using the createGattServer() method.

startAdvertising(deprecated)

startAdvertising(setting: AdvertiseSetting, advData: AdvertiseData, advResponse?: AdvertiseData): void

Starts BLE advertising.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattServer.startAdvertising.

Required permissions: ohos.permission.DISCOVER_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
settingAdvertiseSettingYesSettings related to BLE advertising.
advDataAdvertiseDataYesContent of the BLE advertisement packet.
advResponseAdvertiseDataNoResponse to the BLE scan request.

Return value

No value is returned.

Example

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));
let gattServer : bluetooth.GattServer = bluetooth.BLE.createGattServer();
let setting : bluetooth.AdvertiseSetting = {
    interval:150,
    txPower:60,
    connectable:true,
}

let manufactureData : bluetooth.ManufactureData = {
    manufactureId:4567,
    manufactureValue:manufactureValueBuffer.buffer
}

let serviceData : bluetooth.ServiceData = {
    serviceUuid:"00001888-0000-1000-8000-00805f9b34fb",
    serviceValue:serviceValueBuffer.buffer
}

let advData : bluetooth.AdvertiseData = {
    serviceUuids:["00001889-0000-1000-8000-00805f9b34fb"],
    manufactureData:[manufactureData],
    serviceData:[serviceData],
}

let advResponse : bluetooth.AdvertiseData = {
    serviceUuids:["00001889-0000-1000-8000-00805f9b34fb"],
    manufactureData:[manufactureData],
    serviceData:[serviceData],
}
gattServer.startAdvertising(setting, advData, advResponse);

stopAdvertising(deprecated)

stopAdvertising(): void

Stops BLE advertising.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattServer.stopAdvertising.

Required permissions: ohos.permission.DISCOVER_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

No value is returned.

Example

let server : bluetooth.GattServer = bluetooth.BLE.createGattServer();
server.stopAdvertising();

addService(deprecated)

addService(service: GattService): boolean

Adds a service to this GATT server.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattServer.addService.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
serviceGattServiceYesService to add. Settings related to BLE advertising.

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

// Create descriptors.
let descriptors : Array<bluetooth.BLEDescriptor> = [];
let arrayBuffer = new ArrayBuffer(8);
let descV = new Uint8Array(arrayBuffer);
descV[0] = 11;
let descriptor : bluetooth.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
  descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer};
descriptors[0] = descriptor;

// Create characteristics.
let characteristics : Array<bluetooth.BLECharacteristic> = [];
let arrayBufferC = new ArrayBuffer(8);
let cccV = new Uint8Array(arrayBufferC);
cccV[0] = 1;
let characteristic : bluetooth.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
let characteristicN : bluetooth.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
characteristics[0] = characteristic;

// Create a gattService instance.
let gattService : bluetooth.GattService = {serviceUuid:'00001810-0000-1000-8000-00805F9B34FB', isPrimary: true, characteristics:characteristics, includeServices:[]};

let gattServer : bluetooth.GattServer = bluetooth.BLE.createGattServer();
let ret : boolean = gattServer.addService(gattService);
if (ret) {
   console.log("add service successfully");
} else {
   console.log("add service failed");
}

removeService(deprecated)

removeService(serviceUuid: string): boolean

Removes a service from this GATT server.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattServer.removeService.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
serviceUuidstringYesUniversally unique identifier (UUID) of the service to remove, for example, 00001810-0000-1000-8000-00805F9B34FB.

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

let server : bluetooth.GattServer = bluetooth.BLE.createGattServer();
server.removeService('00001810-0000-1000-8000-00805F9B34FB');

close(deprecated)

close(): void

Closes this GATT server to unregister it from the protocol stack. After this method is called, this GattServer cannot be used.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattServer.close.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Example

let server : bluetooth.GattServer = bluetooth.BLE.createGattServer();
server.close();

notifyCharacteristicChanged(deprecated)

notifyCharacteristicChanged(deviceId: string, notifyCharacteristic: NotifyCharacteristic): boolean

Notifies the connected client device when a characteristic value changes.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattServer.notifyCharacteristicChanged.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
deviceIdstringYesAddress of the client that receives notifications, for example, XX:XX:XX:XX:XX:XX.
notifyCharacteristicNotifyCharacteristicYesNew characteristic value.

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

// Create descriptors.
let descriptors : Array<bluetooth.BLEDescriptor> = [];
let arrayBuffer = new ArrayBuffer(8);
let descV = new Uint8Array(arrayBuffer);
descV[0] = 11;
let descriptor : bluetooth.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
  descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer};
descriptors[0] = descriptor;
let arrayBufferC = new ArrayBuffer(8);
let characteristic : bluetooth.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
let notifyCharacteristic : bluetooth.NotifyCharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: characteristic.characteristicValue, confirm: false};
let server : bluetooth.GattServer = bluetooth.BLE.createGattServer();
server.notifyCharacteristicChanged('XX:XX:XX:XX:XX:XX', notifyCharacteristic);

sendResponse(deprecated)

sendResponse(serverResponse: ServerResponse): boolean

Sends a response to a read or write request from the GATT client.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattServer.sendResponse.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
serverResponseServerResponseYesResponse returned by the GATT server.

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

/* send response */
let arrayBufferCCC = new ArrayBuffer(8);
let cccValue = new Uint8Array(arrayBufferCCC);
cccValue[0] = 1123;
let serverResponse : bluetooth.ServerResponse = {
    "deviceId": "XX:XX:XX:XX:XX:XX",
    "transId": 0,
    "status": 0,
    "offset": 0,
    "value": arrayBufferCCC,
};

let gattServer : bluetooth.GattServer = bluetooth.BLE.createGattServer();
let ret : boolean = gattServer.sendResponse(serverResponse);
if (ret) {
  console.log('bluetooth sendResponse successfully');
} else {
  console.log('bluetooth sendResponse failed');
}

on('characteristicRead')(deprecated)

on(type: "characteristicRead", callback: Callback<CharacteristicReadReq>): void

Subscribes to the characteristic read request events.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattServer.on('characteristicRead').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value characteristicRead indicates a characteristic read request event.
callbackCallback<CharacteristicReadReq>YesCallback invoked to return a characteristic read request event from the GATT client.

Return value

No value is returned.

Example

let arrayBufferCCC = new ArrayBuffer(8);
let cccValue = new Uint8Array(arrayBufferCCC);
cccValue[0] = 1123;
function ReadCharacteristicReq(CharacteristicReadReq : bluetooth.CharacteristicReadReq) {
  let deviceId : string = CharacteristicReadReq.deviceId;
  let transId : number = CharacteristicReadReq.transId;
  let offset : number = CharacteristicReadReq.offset;
  let characteristicUuid : string = CharacteristicReadReq.characteristicUuid;

  let serverResponse : bluetooth.ServerResponse = {deviceId: deviceId, transId: transId, status: 0, 
  offset: offset, value:arrayBufferCCC};

  let ret : boolean = gattServer.sendResponse(serverResponse);
  if (ret) {
    console.log('bluetooth sendResponse successfully');
  } else {
    console.log('bluetooth sendResponse failed');
  }
}

let gattServer : bluetooth.GattServer = bluetooth.BLE.createGattServer();
gattServer.on("characteristicRead", ReadCharacteristicReq);

off('characteristicRead')(deprecated)

off(type: "characteristicRead", callback?: Callback<CharacteristicReadReq>): void

Unsubscribes from the characteristic read request events.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattServer.off('characteristicRead').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value characteristicRead indicates a characteristic read request event.
callbackCallback<CharacteristicReadReq>NoCallback for the characteristic read request event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to type.

Return value

No value is returned.

Example

let gattServer : bluetooth.GattServer = bluetooth.BLE.createGattServer();
gattServer.off("characteristicRead");

on('characteristicWrite')(deprecated)

on(type: "characteristicWrite", callback: Callback<CharacteristicWriteReq>): void

Subscribes to the characteristic write request events.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattServer.on('characteristicWrite').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value characteristicWrite indicates a characteristic write request event.
callbackCallback<CharacteristicWriteReq>YesCallback invoked to return a characteristic write request from the GATT client.

Return value

No value is returned.

Example

let arrayBufferCCC = new ArrayBuffer(8);
let cccValue = new Uint8Array(arrayBufferCCC);
function WriteCharacteristicReq(CharacteristicWriteReq : bluetooth.CharacteristicWriteReq) {
  let deviceId : string = CharacteristicWriteReq.deviceId;
  let transId : number = CharacteristicWriteReq.transId;
  let offset : number = CharacteristicWriteReq.offset;
  let isPrep : boolean = CharacteristicWriteReq.isPrep;
  let needRsp : boolean = CharacteristicWriteReq.needRsp;
  let value =  new Uint8Array(arrayBufferCCC);
  let characteristicUuid : string = CharacteristicWriteReq.characteristicUuid;

  cccValue.set(new Uint8Array(value));
  let serverResponse : bluetooth.ServerResponse = {deviceId: deviceId, transId: transId, status: 0, 
  offset: offset, value:arrayBufferCCC};

  let ret : boolean = gattServer.sendResponse(serverResponse);
  if (ret) {
    console.log('bluetooth sendResponse successfully');
  } else {
    console.log('bluetooth sendResponse failed');
  }
}

let gattServer : bluetooth.GattServer = bluetooth.BLE.createGattServer();
gattServer.on("characteristicWrite", WriteCharacteristicReq);

off('characteristicWrite')(deprecated)

off(type: "characteristicWrite", callback?: Callback<CharacteristicWriteReq>): void

Unsubscribes from the characteristic write request events.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattServer.off('characteristicWrite').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value characteristicWrite indicates a characteristic write request event.
callbackCallback<CharacteristicWriteReq>NoCallback for the characteristic write request event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to type.

Return value

No value is returned.

Example

let gattServer : bluetooth.GattServer = bluetooth.BLE.createGattServer();
gattServer.off("characteristicWrite");

on('descriptorRead')(deprecated)

on(type: "descriptorRead", callback: Callback<DescriptorReadReq>): void

Subscribes to the descriptor read request events.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattServer.on('descriptorRead').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value descriptorRead indicates a descriptor read request event.
callbackCallback<DescriptorReadReq>YesCallback invoked to return a descriptor read request event from the GATT client.

Return value

No value is returned.

Example

let arrayBufferDesc = new ArrayBuffer(8);
let descValue = new Uint8Array(arrayBufferDesc);
descValue[0] = 1101;
function ReadDescriptorReq(DescriptorReadReq : bluetooth.DescriptorReadReq) {
  let deviceId : string = DescriptorReadReq.deviceId;
  let transId : number = DescriptorReadReq.transId;
  let offset : number = DescriptorReadReq.offset;
  let descriptorUuid : string = DescriptorReadReq.descriptorUuid;

  let serverResponse : bluetooth.ServerResponse = {deviceId: deviceId, transId: transId, status: 0, 
  offset: offset, value:arrayBufferDesc};

  let ret : boolean = gattServer.sendResponse(serverResponse);
  if (ret) {
    console.log('bluetooth sendResponse successfully');
  } else {
    console.log('bluetooth sendResponse failed');
  }
}

let gattServer : bluetooth.GattServer = bluetooth.BLE.createGattServer();
gattServer.on("descriptorRead", ReadDescriptorReq);

off('descriptorRead')(deprecated)

off(type: "descriptorRead", callback?: Callback<DescriptorReadReq>): void

Unsubscribes from the descriptor read request events.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattServer.off('descriptorRead').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value descriptorRead indicates a descriptor read request event.
callbackCallback<DescriptorReadReq>NoCallback for the descriptor read request event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to type.

Return value

No value is returned.

Example

let gattServer : bluetooth.GattServer = bluetooth.BLE.createGattServer();
gattServer.off("descriptorRead");

on('descriptorWrite')(deprecated)

on(type: "descriptorWrite", callback: Callback<DescriptorWriteReq>): void

Subscribes to the descriptor write request events.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattServer.on('descriptorWrite').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value descriptorWrite indicates a descriptor write request event.
callbackCallback<DescriptorWriteReq>YesCallback invoked to return a descriptor write request from the GATT client.

Return value

No value is returned.

Example

let arrayBufferDesc = new ArrayBuffer(8);
let descValue = new Uint8Array(arrayBufferDesc);
function WriteDescriptorReq(DescriptorWriteReq : bluetooth.DescriptorWriteReq) {
  let deviceId : string = DescriptorWriteReq.deviceId;
  let transId : number = DescriptorWriteReq.transId;
  let offset : number = DescriptorWriteReq.offset;
  let isPrep : boolean = DescriptorWriteReq.isPrep;
  let needRsp : boolean = DescriptorWriteReq.needRsp;
  let value = new Uint8Array(arrayBufferDesc);
  let descriptorUuid : string = DescriptorWriteReq.descriptorUuid;

  descValue.set(new Uint8Array(value));
  let serverResponse : bluetooth.ServerResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc};

  let ret : boolean = gattServer.sendResponse(serverResponse);
  if (ret) {
    console.log('bluetooth sendResponse successfully');
  } else {
    console.log('bluetooth sendResponse failed');
  }
}

let gattServer : bluetooth.GattServer = bluetooth.BLE.createGattServer();
gattServer.on("descriptorWrite", WriteDescriptorReq);

off('descriptorWrite')(deprecated)

off(type: "descriptorWrite", callback?: Callback<DescriptorWriteReq>): void

Unsubscribes from the descriptor write request events.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattServer.off('descriptorWrite').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value descriptorWrite indicates a descriptor write request event.
callbackCallback<DescriptorWriteReq>NoCallback for the descriptor write request event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to type.

Return value

No value is returned.

Example

let gattServer : bluetooth.GattServer = bluetooth.BLE.createGattServer();
gattServer.off("descriptorWrite");

on('connectStateChange')(deprecated)

on(type: "connectStateChange", callback: Callback<BLEConnectChangedState>): void

Subscribes to the BLE connection state changes.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattServer.on('connectStateChange').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value connectStateChange indicates a BLE connection state change event.
callbackCallback<BLEConnectChangedState>YesCallback invoked to return the BLE connection state.

Return value

No value is returned.

Example

function Connected(BLEConnectChangedState : bluetooth.BLEConnectChangedState) {
  let deviceId : string = BLEConnectChangedState.deviceId;
  let status : bluetooth.ProfileConnectionState = BLEConnectChangedState.state;
}

let gattServer : bluetooth.GattServer = bluetooth.BLE.createGattServer();
gattServer.on("connectStateChange", Connected);

off('connectStateChange')(deprecated)

off(type: "connectStateChange", callback?: Callback<BLEConnectChangedState>): void

Unsubscribes from the BLE connection state changes.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattServer.off('connectStateChange').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value connectStateChange indicates a BLE connection state change event.
callbackCallback<BLEConnectChangedState>NoCallback for the BLE connection state change event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to type.

Return value

No value is returned.

Example

let gattServer : bluetooth.GattServer = bluetooth.BLE.createGattServer();
gattServer.off("connectStateChange");

GattClientDevice

Implements the GATT client. Before using a method of this class, you must create a GattClientDevice instance using the createGattClientDevice(deviceId: string) method.

connect(deprecated)

connect(): boolean

Initiates a connection to the remote BLE device.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.connect.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
booleanReturns true if the connection is successful; returns false otherwise.

Example

let device : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
let ret : boolean = device.connect();

disconnect(deprecated)

disconnect(): boolean

Disconnects from the remote BLE device.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.disconnect.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

let device : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
let ret : boolean = device.disconnect();

close(deprecated)

close(): boolean

Closes this GATT client to unregister it from the protocol stack. After this method is called, this GattClientDevice instance cannot be used.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.close.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

let device : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
let ret : boolean = device.close();

getServices(deprecated)

getServices(callback: AsyncCallback<Array<GattService>>): void

Obtains all services of the remote BLE device. This API uses an asynchronous callback to return the result.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.getServices.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<Array<GattService>>YesCallback invoked to return the services obtained.

Return value

No value is returned.

Example

import { BusinessError } from '@ohos.base';
// Callback
function getServices(code : BusinessError, gattServices : Array<bluetooth.GattService>) {
  if (code.code == 0) {
      let services : Array<bluetooth.GattService> = gattServices;
      console.log('bluetooth code is ' + code.code);
      console.log("bluetooth services size is ", services.length);

      for (let i = 0; i < services.length; i++) {
        console.log('bluetooth serviceUuid is ' + services[i].serviceUuid);
      }
  }
}

let device : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
device.connect();
device.getServices(getServices);

getServices(deprecated)

getServices(): Promise<Array<GattService>>

Obtains all services of the remote BLE device. This API uses a promise to return the result.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.getServices.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
Promise<Array<GattService>>Promise used to return the services obtained.

Example

// Promise
let device : bluetooth.GattClientDevice= bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
device.connect();
device.getServices().then((result : Array<bluetooth.GattService>) => {
    console.info("getServices successfully:" + JSON.stringify(result));
});

readCharacteristicValue(deprecated)

readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback<BLECharacteristic>): void

Reads the characteristic value of the specific service of the remote BLE device. This API uses an asynchronous callback to return the result.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.readCharacteristicValue.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
characteristicBLECharacteristicYesCharacteristic value to read.
callbackAsyncCallback<BLECharacteristic>YesCallback invoked to return the characteristic value read.

Return value

No value is returned.

Example

import { BusinessError } from '@ohos.base';
function readCcc(code : BusinessError, BLECharacteristic : bluetooth.BLECharacteristic) {
  if (code.code != 0) {
      return;
  }
  console.log('bluetooth characteristic uuid: ' + BLECharacteristic.characteristicUuid);
  let value = new Uint8Array(BLECharacteristic.characteristicValue);
  console.log('bluetooth characteristic value: ' + value[0] +','+ value[1]+','+ value[2]+','+ value[3]);
}

let device : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
let descriptors : Array<bluetooth.BLEDescriptor> = [];
let bufferDesc : ArrayBuffer = new ArrayBuffer(8);
let descV : Uint8Array = new Uint8Array(bufferDesc);
descV[0] = 11;
let descriptor : bluetooth.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc};
descriptors[0] = descriptor;

let bufferCCC = new ArrayBuffer(8);
let cccV = new Uint8Array(bufferCCC);
cccV[0] = 1;
let characteristic : bluetooth.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
characteristicValue: bufferCCC, descriptors:descriptors};

device.readCharacteristicValue(characteristic, readCcc);

readCharacteristicValue(deprecated)

readCharacteristicValue(characteristic: BLECharacteristic): Promise<BLECharacteristic>

Reads the characteristic value of the specific service of the remote BLE device. This API uses a promise to return the result.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.readCharacteristicValue.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
characteristicBLECharacteristicYesCharacteristic value to read.

Return value

TypeDescription
Promise<BLECharacteristic>Promise used to return the characteristic value read.

Example

let device : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
let descriptors : Array<bluetooth.BLEDescriptor> = [];
let bufferDesc = new ArrayBuffer(8);
let descV = new Uint8Array(bufferDesc);
descV[0] = 11;
let descriptor : bluetooth.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc};
descriptors[0] = descriptor;

let bufferCCC = new ArrayBuffer(8);
let cccV = new Uint8Array(bufferCCC);
cccV[0] = 1;
let characteristic : bluetooth.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
characteristicValue: bufferCCC, descriptors:descriptors};

device.readCharacteristicValue(characteristic);

readDescriptorValue(deprecated)

readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback<BLEDescriptor>): void

Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses an asynchronous callback to return the result.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.readDescriptorValue.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
descriptorBLEDescriptorYesDescriptor to read.
callbackAsyncCallback<BLEDescriptor>YesCallback invoked to return the descriptor read.

Return value

No value is returned.

Example

import { BusinessError } from '@ohos.base';
function readDesc(code : BusinessError, BLEDescriptor : bluetooth.BLEDescriptor) {
  if (code.code != 0) {
      return;
  }
  console.log('bluetooth descriptor uuid: ' + BLEDescriptor.descriptorUuid);
  let value = new Uint8Array(BLEDescriptor.descriptorValue);
  console.log('bluetooth descriptor value: ' + value[0] +','+ value[1]+','+ value[2]+','+ value[3]);
}

let device : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
let bufferDesc = new ArrayBuffer(8);
let descV = new Uint8Array(bufferDesc);
descV[0] = 11;
let descriptor : bluetooth.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
  descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc};
device.readDescriptorValue(descriptor, readDesc);

readDescriptorValue(deprecated)

readDescriptorValue(descriptor: BLEDescriptor): Promise<BLEDescriptor>

Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses a promise to return the result.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.readDescriptorValue.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
descriptorBLEDescriptorYesDescriptor to read.

Return value

TypeDescription
Promise<BLEDescriptor>Promise used to return the descriptor read.

Example

let device : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
let bufferDesc = new ArrayBuffer(8);
let descV = new Uint8Array(bufferDesc);
descV[0] = 11;
let descriptor : bluetooth.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
  descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc};
device.readDescriptorValue(descriptor);

writeCharacteristicValue(deprecated)

writeCharacteristicValue(characteristic: BLECharacteristic): boolean

Writes a characteristic value to the remote BLE device.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.writeCharacteristicValue.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
characteristicBLECharacteristicYesBinary value and other parameters of the BLE device characteristic.

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

let device : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
let descriptors : Array<bluetooth.BLEDescriptor> = [];
let bufferDesc = new ArrayBuffer(8);
let descV = new Uint8Array(bufferDesc);
descV[0] = 11;
let descriptor : bluetooth.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
  descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc};
descriptors[0] = descriptor;

let bufferCCC = new ArrayBuffer(8);
let cccV = new Uint8Array(bufferCCC);
cccV[0] = 1;
let characteristic : bluetooth.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
  characteristicValue: bufferCCC, descriptors:descriptors};
let retWriteCcc : boolean = device.writeCharacteristicValue(characteristic);
if (retWriteCcc) {
  console.log('write characteristic successfully');
} else {
  console.log('write characteristic failed');
}

writeDescriptorValue(deprecated)

writeDescriptorValue(descriptor: BLEDescriptor): boolean

Writes binary data to the specific descriptor of the remote BLE device.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.writeDescriptorValue.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
descriptorBLEDescriptorYesBinary value and other parameters of the BLE device descriptor.

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

let device : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
let bufferDesc = new ArrayBuffer(8);
let descV = new Uint8Array(bufferDesc);
descV[0] = 22;
let descriptor : bluetooth.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
  descriptorUuid: '00002903-0000-1000-8000-00805F9B34FB', descriptorValue: bufferDesc};
let retWriteDesc : boolean = device.writeDescriptorValue(descriptor);
if (retWriteDesc) {
  console.log('bluetooth write descriptor successfully');
} else {
  console.log('bluetooth write descriptor failed');
}

setBLEMtuSize(deprecated)

setBLEMtuSize(mtu: number): boolean

Sets the maximum transmission unit (MTU) that can be transmitted between the GATT client and its remote BLE device. This API can be used only after a connection is set up by calling connect.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.setBLEMtuSize.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
mtunumberYesMTU to set, which ranges from 22 to 512 bytes.

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

let device : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
device.setBLEMtuSize(128);

setNotifyCharacteristicChanged(deprecated)

setNotifyCharacteristicChanged(characteristic: BLECharacteristic, enable: boolean): boolean

Sets the function of notifying the GATT client when the characteristic value of the remote BLE device changes.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.setNotifyCharacteristicChanged.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
characteristicBLECharacteristicYesBLE characteristic to listen for.
enablebooleanYesWhether to enable the notify function. The value true means to enable the notify function, and the value false means the opposite.

Return value

TypeDescription
booleanReturns true if the operation is successful; returns false otherwise.

Example

// Create descriptors.
let descriptors : Array<bluetooth.BLEDescriptor> = [];
let arrayBuffer = new ArrayBuffer(8);
let descV = new Uint8Array(arrayBuffer);
descV[0] = 11;
let descriptor : bluetooth.BLEDescriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
  descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer};
descriptors[0] = descriptor;
let arrayBufferC = new ArrayBuffer(8);
let characteristic : bluetooth.BLECharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
  characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
let device : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
device.setNotifyCharacteristicChanged(characteristic, false);

on('BLECharacteristicChange')(deprecated)

on(type: "BLECharacteristicChange", callback: Callback<BLECharacteristic>): void

Subscribes to the BLE characteristic changes. The client can receive a notification from the server only after the setNotifyCharacteristicChanged method is called.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.on('BLECharacteristicChange').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value BLECharacteristicChange indicates a characteristic value change event.
callbackCallback<BLECharacteristic>YesCallback invoked to return the characteristic value changes.

Return value

No value is returned.

Example

function CharacteristicChange(CharacteristicChangeReq : bluetooth.BLECharacteristic) {
  let serviceUuid : string = CharacteristicChangeReq.serviceUuid;
  let characteristicUuid : string = CharacteristicChangeReq.characteristicUuid;
  let value = new Uint8Array(CharacteristicChangeReq.characteristicValue);
}
let device : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
device.on('BLECharacteristicChange', CharacteristicChange);

off('BLECharacteristicChange')(deprecated)

off(type: "BLECharacteristicChange", callback?: Callback<BLECharacteristic>): void

Unsubscribes from the BLE characteristic changes.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.off('BLECharacteristicChange').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value BLECharacteristicChange indicates a characteristic value change event.
callbackCallback<BLECharacteristic>NoCallback for the characteristic value change event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to type.

Return value

No value is returned.

Example

let device : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
device.off('BLECharacteristicChange');

on('BLEConnectionStateChange')(deprecated)

on(type: "BLEConnectionStateChange", callback: Callback<BLEConnectChangedState>): void

Subscribes to the BLE connection state changes.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.on('BLEConnectionStateChange').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value BLEConnectionStateChange indicates a BLE connection state change event.
callbackCallback<BLEConnectChangedState>YesCallback invoked to return the BLE connection state.

Return value

No value is returned.

Example

function ConnectStateChanged(state : bluetooth.BLEConnectChangedState) {
  console.log('bluetooth connect state changed');
  let connectState : bluetooth.ProfileConnectionState = state.state;
}
let device : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
device.on('BLEConnectionStateChange', ConnectStateChanged);

off('BLEConnectionStateChange')(deprecated)

off(type: "BLEConnectionStateChange", callback?: Callback<BLEConnectChangedState>): void

Unsubscribes from the BLE connection state changes.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.off('BLEConnectionStateChange').

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value BLEConnectionStateChange indicates a BLE connection state change event.
callbackCallback<BLEConnectChangedState>NoCallback for the BLE connection state change event. If this parameter is not set, this method unsubscribes from all callbacks corresponding to type.

Return value

No value is returned.

Example

let device : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
device.off('BLEConnectionStateChange');

getDeviceName(deprecated)

getDeviceName(callback: AsyncCallback<string>): void

Obtains the name of the remote BLE device. This API uses an asynchronous callback to return the result.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.getDeviceName.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<string>YesCallback invoked to return the remote BLE device name obtained.

Return value

No value is returned.

Example

import { BusinessError } from '@ohos.base';
// callback
let gattClient : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice("XX:XX:XX:XX:XX:XX");
let deviceName : void = gattClient.getDeviceName((err : BusinessError, data : string)=> {
    console.info('device name err ' + JSON.stringify(err));
    console.info('device name' + JSON.stringify(data));
})

getDeviceName(deprecated)

getDeviceName(): Promise<string>

Obtains the name of the remote BLE device. This API uses a promise to return the result.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.getDeviceName.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
Promise<string>Promise used to return the remote BLE device name.

Example

// promise
let gattClient : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice("XX:XX:XX:XX:XX:XX");
gattClient.getDeviceName().then((data) => {
    console.info('device name' + JSON.stringify(data));
})

getRssiValue(deprecated)

getRssiValue(callback: AsyncCallback<number>): void

Obtains the received signal strength indication (RSSI) of the remote BLE device. This API uses an asynchronous callback to return the result. It can be used only after a connection is set up by calling connect.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.getRssiValue.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<number>YesCallback invoked to return the RSSI, in dBm.

Return value

No value is returned.

Example

import { BusinessError } from '@ohos.base';
// callback
let gattClient : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice("XX:XX:XX:XX:XX:XX");
let ret : boolean = gattClient.connect();
gattClient.getRssiValue((err : BusinessError, data : number)=> {
    console.info('rssi err ' + JSON.stringify(err));
    console.info('rssi value' + JSON.stringify(data));
})

getRssiValue(deprecated)

getRssiValue(): Promise<number>

Obtains the RSSI of the remote BLE device. This API uses a promise to return the result. It can be used only after a connection is set up by calling connect.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattClientDevice.getRssiValue.

Required permissions: ohos.permission.USE_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
Promise<number>Promise used to return the RSSI, in dBm.

Example

// promise
let gattClient : bluetooth.GattClientDevice = bluetooth.BLE.createGattClientDevice("XX:XX:XX:XX:XX:XX");
gattClient.getRssiValue().then((data : number) => {
    console.info('rssi' + JSON.stringify(data));
})

ScanMode8+(deprecated)

Enumerates the scan modes.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.ScanMode.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
SCAN_MODE_NONE0No scan mode.
SCAN_MODE_CONNECTABLE1Connectable mode.
SCAN_MODE_GENERAL_DISCOVERABLE2General discoverable mode.
SCAN_MODE_LIMITED_DISCOVERABLE3Limited discoverable mode.
SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE4General connectable and discoverable mode.
SCAN_MODE_CONNECTABLE_LIMITED_DISCOVERABLE5Limited connectable and discoverable mode.

BondState8+(deprecated)

Enumerates the pairing states.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.BondState.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
BOND_STATE_INVALID0Invalid pairing.
BOND_STATE_BONDING1Pairing.
BOND_STATE_BONDED2Paired.

SppOption8+(deprecated)

Defines the SPP configuration parameters.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.SppOption.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
uuidstringYesYesUUID of the SPP.
securebooleanYesYesWhether it is a secure channel.
typeSppTypeYesYesType of the SPP link.

SppType8+(deprecated)

Enumerates the SPP link types.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.SppType.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
SPP_RFCOMM0Radio frequency communication (RFCOMM) link type.

GattService(deprecated)

Defines the GATT service API parameters.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.GattService.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
serviceUuidstringYesYesUUID of the service, for example, 00001888-0000-1000-8000-00805f9b34fb.
isPrimarybooleanYesYesWhether the service is a primary service. The value true means a primary service.
characteristicsArray<BLECharacteristic>YesYesList of characteristics of the service.
includeServicesArray<GattService>YesYesServices on which the service depends.

BLECharacteristic(deprecated)

Defines the characteristic API parameters.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.BLECharacteristic.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
serviceUuidstringYesYesUUID of the service, for example, 00001888-0000-1000-8000-00805f9b34fb.
characteristicUuidstringYesYesUUID of the characteristic, for example, 00002a11-0000-1000-8000-00805f9b34fb.
characteristicValueArrayBufferYesYesBinary value of the characteristic.
descriptorsArray<BLEDescriptor>YesYesList of descriptors of the characteristic.

BLEDescriptor(deprecated)

Defines the descriptor API parameters.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.BLEDescriptor.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
serviceUuidstringYesYesUUID of the service, for example, 00001888-0000-1000-8000-00805f9b34fb.
characteristicUuidstringYesYesUUID of the characteristic, for example, 00002a11-0000-1000-8000-00805f9b34fb.
descriptorUuidstringYesYesUUID of the descriptor, for example, 00002902-0000-1000-8000-00805f9b34fb.
descriptorValueArrayBufferYesYesBinary value of the descriptor.

NotifyCharacteristic(deprecated)

Defines the parameters in the notifications sent when the server characteristic value changes.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.NotifyCharacteristic.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
serviceUuidstringYesYesUUID of the service, for example, 00001888-0000-1000-8000-00805f9b34fb.
characteristicUuidstringYesYesUUID of the characteristic, for example, 00002a11-0000-1000-8000-00805f9b34fb.
characteristicValueArrayBufferYesYesBinary value of the characteristic.
confirmbooleanYesYesWhether the notification needs to be confirmed by the remote end. For a notification, set it to true. In this case, the remote end must confirm the receipt of the notification. For an indication, set it to false. In this case, the remote end does not need to confirm the receipt of the notification.

CharacteristicReadReq(deprecated)

Defines the parameters of the CharacteristicReadReq event received by the server.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.CharacteristicReadRequest.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesNoAddress of the remote device that sends the CharacteristicReadReq event, for example, XX:XX:XX:XX:XX:XX.
transIdnumberYesNoTransmission ID of the read request. The response returned by the server must use the same transmission ID.
offsetnumberYesNoPosition from which the characteristic value is read. For example, k means to read from the kth byte. The response returned by the server must use the same offset.
characteristicUuidstringYesNoUUID of the characteristic, for example, 00002a11-0000-1000-8000-00805f9b34fb.
serviceUuidstringYesNoUUID of the service, for example, 00001888-0000-1000-8000-00805f9b34fb.

CharacteristicWriteReq(deprecated)

Defines the parameters of the CharacteristicWriteReq event received by the server.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.CharacteristicWriteRequest.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesNoAddress of the remote device that sends the CharacteristicWriteReq event, for example, XX:XX:XX:XX:XX:XX.
transIdnumberYesNoTransmission ID of the write request. The response returned by the server must use the same transmission ID.
offsetnumberYesNoStart position for writing the characteristic value. For example, k means to write from the kth byte. The response returned by the server must use the same offset.
descriptorUuidstringYesNoUUID of the descriptor, for example, 00002902-0000-1000-8000-00805f9b34fb.
characteristicUuidstringYesNoUUID of the characteristic, for example, 00002a11-0000-1000-8000-00805f9b34fb.
serviceUuidstringYesNoUUID of the service, for example, 00001888-0000-1000-8000-00805f9b34fb.

DescriptorReadReq(deprecated)

Defines the parameters of the DescriptorReadReq event received by the server.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.DescriptorReadRequest.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesNoAddress of the remote device that sends a DescriptorReadReq event, for example, XX:XX:XX:XX:XX:XX.
transIdnumberYesNoTransmission ID of the read request. The response returned by the server must use the same transmission ID.
offsetnumberYesNoPosition from which the descriptor is read. For example, k means to read from the kth byte. The response returned by the server must use the same offset.
descriptorUuidstringYesNoUUID of the descriptor, for example, 00002902-0000-1000-8000-00805f9b34fb.
characteristicUuidstringYesNoUUID of the characteristic, for example, 00002a11-0000-1000-8000-00805f9b34fb.
serviceUuidstringYesNoUUID of the service, for example, 00001888-0000-1000-8000-00805f9b34fb.

DescriptorWriteReq(deprecated)

Defines the parameters of the DescriptorWriteReq event received by the server.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.DescriptorWriteRequest.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesNoAddress of the remote device that sends a DescriptorWriteReq event, for example, XX:XX:XX:XX:XX:XX.
transIdnumberYesNoTransmission ID of the write request. The response returned by the server must use the same transmission ID.
offsetnumberYesNoStart position for writing the descriptor. For example, k means to write from the kth byte. The response returned by the server must use the same offset.
isPrepbooleanYesNoWhether the write request is executed immediately.
needRspbooleanYesNoWhether to send a response to the GATT client.
valueArrayBufferYesNoBinary value of the descriptor to write.
descriptorUuidstringYesNoUUID of the descriptor, for example, 00002902-0000-1000-8000-00805f9b34fb.
characteristicUuidstringYesNoUUID of the characteristic, for example, 00002a11-0000-1000-8000-00805f9b34fb.
serviceUuidstringYesNoUUID of the service, for example, 00001888-0000-1000-8000-00805f9b34fb.

ServerResponse(deprecated)

Defines the parameters of the server's response to the GATT client's read/write request.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.ServerResponse.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesNoAddress of the remote device, for example, XX:XX:XX:XX:XX:XX.
transIdnumberYesNoTransmission ID of the request. The value must be the same as the ID carried in the read/write request received.
statusnumberYesNoResponse state. Set this parameter to 0, which indicates a normal response.
offsetnumberYesNoStart read/write position. The value must be the same as the offset carried in the read/write request.
valueArrayBufferYesNoBinary data in the response.

BLEConnectChangedState(deprecated)

Defines the parameters of BLEConnectChangedState.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.BLEConnectChangedState.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesNoAddress of the remote device, for example, XX:XX:XX:XX:XX:XX.
stateProfileConnectionStateYesYesBLE connection state.

ProfileConnectionState(deprecated)

Enumerates the profile connection states.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.ProfileConnectionState.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
STATE_DISCONNECTED0Disconnected.
STATE_CONNECTING1Connecting.
STATE_CONNECTED2Connected.
STATE_DISCONNECTING3Disconnecting.

ScanFilter(deprecated)

Defines the scan filter parameters.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.ScanFilter.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesYesAddress of the BLE device to filter, for example, XX:XX:XX:XX:XX:XX.
namestringYesYesName of the BLE device to filter.
serviceUuidstringYesYesService UUID of the device to filter, for example, 00001888-0000-1000-8000-00805f9b34fb.

ScanOptions(deprecated)

Defines the scan configuration parameters.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.ScanOptions.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
intervalnumberYesYesDelay in reporting the scan result. The default value is 0.
dutyModeScanDutyYesYesScan duty. The default value is SCAN_MODE_LOW_POWER.
matchModeMatchModeYesYesHardware filtering match mode. The default value is MATCH_MODE_AGGRESSIVE.

ScanDuty(deprecated)

Enumerates the scan duty options.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.ScanDuty.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
SCAN_MODE_LOW_POWER0Low-power mode, which is the default value.
SCAN_MODE_BALANCED1Balanced mode.
SCAN_MODE_LOW_LATENCY2Low-latency mode.

MatchMode(deprecated)

Enumerates the hardware match modes of BLE scan filters.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.MatchMode.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
MATCH_MODE_AGGRESSIVE1Hardware reports the scan result with a lower threshold of signal strength and few number of matches in a duration. This is the default value.
MATCH_MODE_STICKY2Hardware reports the scan result with a higher threshold of signal strength and sightings.

ScanResult(deprecated)

Defines the scan result.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.ScanResult.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesNoAddress of the scanned device, for example, XX:XX:XX:XX:XX:XX.
rssinumberYesNoRSSI of the device.
dataArrayBufferYesNoAdvertisement packets sent by the device.

BluetoothState(deprecated)

Enumerates the Bluetooth states.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.BluetoothState.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
STATE_OFF0Bluetooth is turned off.
STATE_TURNING_ON1Bluetooth is being turned on.
STATE_ON2Bluetooth is turned on.
STATE_TURNING_OFF3Bluetooth is being turned off.
STATE_BLE_TURNING_ON4The LE-only mode is being turned on for Bluetooth.
STATE_BLE_ON5Bluetooth is in LE-only mode.
STATE_BLE_TURNING_OFF6The LE-only mode is being turned off for Bluetooth.

AdvertiseSetting(deprecated)

Defines the BLE advertising parameters.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.AdvertiseSetting.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
intervalnumberYesYesInterval for BLE advertising. The minimum value is 32 slots (20 ms). The maximum value is 16384 slots. The default value is 1600 slots (1s).
txPowernumberYesYesTransmit power, in dBm. The value range is -127 to 1. The default value is -7.
connectablebooleanYesYesWhether the advertisement is connectable. The default value is true.

AdvertiseData(deprecated)

Defines the content of a BLE advertisement packet.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.AdvertiseData.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
serviceUuidsArray<string>YesYesList of service UUIDs to broadcast.
manufactureDataArray<ManufactureData>YesYesList of manufacturers to broadcast.
serviceDataArray<ServiceData>YesYesList of service data to broadcast.

ManufactureData(deprecated)

Defines the content of a BLE advertisement packet.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.ManufactureData.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
manufactureIdnumberYesYesManufacturer ID allocated by the Bluetooth SIG.
manufactureValueArrayBufferYesYesManufacturer data.

ServiceData(deprecated)

Defines the service data contained in an advertisement packet.

NOTE
This API is supported since API version 7 and deprecated since API version 9. You are advised to use bluetoothManager.ServiceData.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
serviceUuidstringYesYesService UUID.
serviceValueArrayBufferYesYesService data.

PinRequiredParam8+(deprecated)

Defines the pairing request parameters.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.PinRequiredParam.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesNoID of the device to pair.
pinCodestringYesNoKey for the device pairing.

BondStateParam8+(deprecated)

Defines the pairing state parameters.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.BondStateParam.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesNoID of the device to pair.
stateBondStateYesNoState of the device.

StateChangeParam8+(deprecated)

Defines the profile state change parameters.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.StateChangeParam.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesNoAddress of a Bluetooth device.
stateProfileConnectionStateYesNoProfile connection state of the device.

DeviceClass8+(deprecated)

Defines the class of a Bluetooth device.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.DeviceClass.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
majorClassMajorClassYesNoMajor classes of Bluetooth devices.
majorMinorClassMajorMinorClassYesNoMajor and minor classes of Bluetooth devices.
classOfDevicenumberYesNoClass of the device.

MajorClass8+(deprecated)

Enumerates the major classes of Bluetooth devices.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.MajorClass.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
MAJOR_MISC0x0000Miscellaneous device.
MAJOR_COMPUTER0x0100Computer.
MAJOR_PHONE0x0200Mobile phone.
MAJOR_NETWORKING0x0300Network device.
MAJOR_AUDIO_VIDEO0x0400Audio or video device.
MAJOR_PERIPHERAL0x0500Peripheral device.
MAJOR_IMAGING0x0600Imaging device.
MAJOR_WEARABLE0x0700Wearable device.
MAJOR_TOY0x0800Toy.
MAJOR_HEALTH0x0900Health device.
MAJOR_UNCATEGORIZED0x1F00Unclassified device.

MajorMinorClass8+(deprecated)

Enumerates the major and minor classes of Bluetooth devices.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.MajorMinorClass.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
COMPUTER_UNCATEGORIZED0x0100Unclassified computer.
COMPUTER_DESKTOP0x0104Desktop computer.
COMPUTER_SERVER0x0108Server.
COMPUTER_LAPTOP0x010CLaptop.
COMPUTER_HANDHELD_PC_PDA0x0110Hand-held computer.
COMPUTER_PALM_SIZE_PC_PDA0x0114Palmtop computer.
COMPUTER_WEARABLE0x0118Wearable computer.
COMPUTER_TABLET0x011CTablet.
PHONE_UNCATEGORIZED0x0200Unclassified mobile phone.
PHONE_CELLULAR0x0204Portable phone.
PHONE_CORDLESS0x0208Cordless phone.
PHONE_SMART0x020CSmartphone.
PHONE_MODEM_OR_GATEWAY0x0210Modem or gateway phone.
PHONE_ISDN0x0214ISDN phone.
NETWORK_FULLY_AVAILABLE0x0300Device with network fully available.
NETWORK_1_TO_17_UTILIZED0x0320Device used on network 1 to 17.
NETWORK_17_TO_33_UTILIZED0x0340Device used on network 17 to 33.
NETWORK_33_TO_50_UTILIZED0x0360Device used on network 33 to 50.
NETWORK_60_TO_67_UTILIZED0x0380Device used on network 60 to 67.
NETWORK_67_TO_83_UTILIZED0x03A0Device used on network 67 to 83.
NETWORK_83_TO_99_UTILIZED0x03C0Device used on network 83 to 99.
NETWORK_NO_SERVICE0x03E0Device without network service
AUDIO_VIDEO_UNCATEGORIZED0x0400Unclassified audio or video device.
AUDIO_VIDEO_WEARABLE_HEADSET0x0404Wearable audio or video headset.
AUDIO_VIDEO_HANDSFREE0x0408Hands-free audio or video device.
AUDIO_VIDEO_MICROPHONE0x0410Audio or video microphone.
AUDIO_VIDEO_LOUDSPEAKER0x0414Audio or video loudspeaker.
AUDIO_VIDEO_HEADPHONES0x0418Audio or video headphones.
AUDIO_VIDEO_PORTABLE_AUDIO0x041CPortable audio or video device.
AUDIO_VIDEO_CAR_AUDIO0x0420In-vehicle audio or video device.
AUDIO_VIDEO_SET_TOP_BOX0x0424Audio or video STB device.
AUDIO_VIDEO_HIFI_AUDIO0x0428High-fidelity speaker device.
AUDIO_VIDEO_VCR0x042CVideo cassette recording (VCR) device.
AUDIO_VIDEO_VIDEO_CAMERA0x0430Camera.
AUDIO_VIDEO_CAMCORDER0x0434Camcorder
AUDIO_VIDEO_VIDEO_MONITOR0x0438Audio or video monitor.
AUDIO_VIDEO_VIDEO_DISPLAY_AND_LOUDSPEAKER0x043CVideo display or loudspeaker.
AUDIO_VIDEO_VIDEO_CONFERENCING0x0440Video conferencing device.
AUDIO_VIDEO_VIDEO_GAMING_TOY0x0448Audio or video gaming toy.
PERIPHERAL_NON_KEYBOARD_NON_POINTING0x0500Non-keyboard or non-pointing peripheral device.
PERIPHERAL_KEYBOARD0x0540Keyboard device.
PERIPHERAL_POINTING_DEVICE0x0580Pointing peripheral device.
PERIPHERAL_KEYBOARD_POINTING0x05C0Keyboard pointing device.
PERIPHERAL_UNCATEGORIZED0x0500Unclassified peripheral device.
PERIPHERAL_JOYSTICK0x0504Peripheral joystick.
PERIPHERAL_GAMEPAD0x0508Peripheral game pad
PERIPHERAL_REMOTE_CONTROL0x05C0Peripheral remote control device
PERIPHERAL_SENSING_DEVICE0x0510Peripheral sensing device.
PERIPHERAL_DIGITIZER_TABLET0x0514Peripheral digitizer tablet.
PERIPHERAL_CARD_READER0x0518Peripheral card reader.
PERIPHERAL_DIGITAL_PEN0x051CPeripheral digital pen.
PERIPHERAL_SCANNER_RFID0x0520Peripheral RFID scanner.
PERIPHERAL_GESTURAL_INPUT0x0522Gesture input device.
IMAGING_UNCATEGORIZED0x0600Unclassified imaging device.
IMAGING_DISPLAY0x0610Imaging display device.
IMAGING_CAMERA0x0620Imaging camera device.
IMAGING_SCANNER0x0640Imaging scanner.
IMAGING_PRINTER0x0680Imaging printer.
WEARABLE_UNCATEGORIZED0x0700Unclassified wearable device.
WEARABLE_WRIST_WATCH0x0704Smart watch.
WEARABLE_PAGER0x0708Wearable pager.
WEARABLE_JACKET0x070CSmart jacket.
WEARABLE_HELMET0x0710Wearable helmet.
WEARABLE_GLASSES0x0714Wearable glasses.
TOY_UNCATEGORIZED0x0800Unclassified toy.
TOY_ROBOT0x0804Toy robot.
TOY_VEHICLE0x0808Toy vehicle.
TOY_DOLL_ACTION_FIGURE0x080CHumanoid toy doll.
TOY_CONTROLLER0x0810Toy controller.
TOY_GAME0x0814Toy gaming device.
HEALTH_UNCATEGORIZED0x0900Unclassified health devices.
HEALTH_BLOOD_PRESSURE0x0904Blood pressure device.
HEALTH_THERMOMETER0x0908Thermometer
HEALTH_WEIGHING0x090CBody scale.
HEALTH_GLUCOSE0x0910Blood glucose monitor.
HEALTH_PULSE_OXIMETER0x0914Pulse oximeter.
HEALTH_PULSE_RATE0x0918Heart rate monitor.
HEALTH_DATA_DISPLAY0x091CHealth data display.
HEALTH_STEP_COUNTER0x0920Step counter.
HEALTH_BODY_COMPOSITION_ANALYZER0x0924Body composition analyzer.
HEALTH_PEAK_FLOW_MOITOR0x0928Hygrometer.
HEALTH_MEDICATION_MONITOR0x092CMedication monitor.
HEALTH_KNEE_PROSTHESIS0x0930Prosthetic knee.
HEALTH_ANKLE_PROSTHESIS0x0934Prosthetic ankle.
HEALTH_GENERIC_HEALTH_MANAGER0x0938Generic health management device.
HEALTH_PERSONAL_MOBILITY_DEVICE0x093CPersonal mobility device.

PlayingState8+(deprecated)

Enumerates the A2DP playing states.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.PlayingState.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
STATE_NOT_PLAYING0x0000Not playing.
STATE_PLAYING0x0001Playing.

ProfileId8+(deprecated)

Enumerates the Bluetooth profiles. API version 9 is added with PROFILE_HID_HOST and PROFILE_PAN_NETWORK.

NOTE
This API is supported since API version 8 and deprecated since API version 9. You are advised to use bluetoothManager.ProfileId.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
PROFILE_A2DP_SOURCE1A2DP profile.
PROFILE_HANDS_FREE_AUDIO_GATEWAY4HFP profile.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙APIs

harmony 鸿蒙System Common Events (To Be Deprecated Soon)

harmony 鸿蒙System Common Events

harmony 鸿蒙API Reference Document Description

harmony 鸿蒙Enterprise Device Management Overview (for System Applications Only)

harmony 鸿蒙BundleStatusCallback

harmony 鸿蒙@ohos.bundle.innerBundleManager (innerBundleManager)

harmony 鸿蒙@ohos.distributedBundle (Distributed Bundle Management)

harmony 鸿蒙@ohos.bundle (Bundle)

harmony 鸿蒙@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/5a9d51e4eaeb4a0390e6dffddb1264ed