openharmony 鸿蒙 js-apis-bluetooth-connection

2025-06-12 浏览 (1)

@ohos.bluetooth.connection (Bluetooth Connection Module)

The connection module provides APIs for operating and managing Bluetooth.

NOTE

The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.

Modules to Import

import { connection } from '@kit.ConnectivityKit';

ProfileConnectionState

type ProfileConnectionState = constant.ProfileConnectionState

Defines the profile connection status of the Bluetooth device.

System capability: SystemCapability.Communication.Bluetooth.Core

TypeDescription
constant.ProfileConnectionStateProfile connection status of the Bluetooth device.

ProfileId

type ProfileId = constant.ProfileId

Enumerates profiles of the Bluetooth device.

System capability: SystemCapability.Communication.Bluetooth.Core

TypeDescription
constant.ProfileIdProfile of the Bluetooth device.

ProfileUuids12+

type ProfileUuids = constant.ProfileUuids

Defines the UUID of a profile.

System capability: SystemCapability.Communication.Bluetooth.Core

TypeDescription
constant.ProfileUuidsUUID of the profile.

MajorClass

type MajorClass = constant.MajorClass

Main class of the Bluetooth device.

System capability: SystemCapability.Communication.Bluetooth.Core

TypeDescription
constant.MajorClassMain class of the Bluetooth device.

MajorMinorClass

type MajorMinorClass = constant.MajorMinorClass

Major and minor classes of the Bluetooth device.

System capability: SystemCapability.Communication.Bluetooth.Core

TypeDescription
constant.MajorMinorClassMajor and minor classes of the Bluetooth device.

connection.pairDevice

pairDevice(deviceId: string, callback: AsyncCallback<void>): void

Pairs a Bluetooth device. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
deviceIdstringYesAddress of the device to pair, for example, XX:XX:XX:XX:XX:XX.
callbackAsyncCallback<void>YesCallback used to return the result. If the pairing is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
// callback
try {
    connection.pairDevice('11:22:33:44:55:66', (err: BusinessError) => {
        console.info('pairDevice, device name err:' + JSON.stringify(err));
    });
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.pairDevice

pairDevice(deviceId: string): Promise<void>

Pairs a Bluetooth device. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

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

Return value

TypeDescription
Promise<void>Promise used to return the result.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
// promise
try {
    connection.pairDevice('11:22:33:44:55:66').then(() => {
        console.info('pairDevice');
    }, (error: BusinessError) => {
        console.info('pairDevice: errCode:' + error.code + ',errMessage' + error.message);
    })

} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getRemoteDeviceName

getRemoteDeviceName(deviceId: string): string

Obtains the name of a remote Bluetooth device.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

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

Return value

TypeDescription
stringDevice name (a string) obtained.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    let remoteDeviceName: string = connection.getRemoteDeviceName('XX:XX:XX:XX:XX:XX');
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getRemoteDeviceName16+

getRemoteDeviceName(deviceId: string, alias?: boolean): string

Obtains the name of the peer device. The alias parameter is optional.

  • If the alias parameter is specified, the application determines whether to obtain the alias of the peer device.
  • If the alias parameter is not specified, the alias of the peer device is returned by default.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 16.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
deviceIdstringYesAddress of the peer device, for example, XX:XX:XX:XX:XX:XX.
aliasbooleanNoWhether to obtain the alias of the peer device. The value true means to obtain the alias, and the value false means the opposite.

Return value

TypeDescription
stringDevice name (a string) obtained.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Failed to obtain the name or alias of the peer Bluetooth device.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    let remoteDeviceName: string = connection.getRemoteDeviceName('XX:XX:XX:XX:XX:XX', true);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getRemoteDeviceClass

getRemoteDeviceClass(deviceId: string): DeviceClass

Obtains the class of a remote Bluetooth device. Since API version 18, the ohos.permission.ACCESS_BLUETOOTH permission is no longer verified.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

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

Return value

TypeDescription
DeviceClassClass of the peer device obtained.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    let remoteDeviceClass: connection.DeviceClass = connection.getRemoteDeviceClass('XX:XX:XX:XX:XX:XX');
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getRemoteProfileUuids12+

getRemoteProfileUuids(deviceId: string, callback: AsyncCallback<Array<ProfileUuids>>): void

Obtains the profile UUIDs of a remote Bluetooth device. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
deviceIdstringYesAddress of the device to pair, for example, XX:XX:XX:XX:XX:XX.
callbackAsyncCallback<Array<ProfileUuids>>YesCallback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Invalid parameter.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    connection.getRemoteProfileUuids('XX:XX:XX:XX:XX:XX', (err: BusinessError, data: Array<connection.ProfileUuids>) => {
        console.info('getRemoteProfileUuids, err: ' + JSON.stringify(err) + ', data: ' + JSON.stringify(data));
    });
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getRemoteProfileUuids12+

getRemoteProfileUuids(deviceId: string): Promise<Array<ProfileUuids>>

Obtains the profile UUIDs of a remote Bluetooth device. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

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

Return value

TypeDescription
Promise<Array<ProfileUuids>>Promise used to return the result.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Invalid parameter.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    connection.getRemoteProfileUuids('XX:XX:XX:XX:XX:XX').then(() => {
        console.info('getRemoteProfileUuids');
    }, (err: BusinessError) => {
        console.error('getRemoteProfileUuids: errCode' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
    });
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getLocalName

getLocalName(): string

Obtains the name of the local Bluetooth device.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
stringName of the local Bluetooth device obtained.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
801Capability not supported.
2900001Service stopped.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    let localName: string = connection.getLocalName();
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getPairedDevices

getPairedDevices(): Array<string>

Obtains the paired devices.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
Array<string>Addresses of the paired Bluetooth devices.
- For security purposes, the device addresses obtained are random MAC addresses.
- The random MAC address remains unchanged after a device is paired successfully.
- The random address changes when the paired device is unpaired and scanned again or the Bluetooth service is turned off.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    let devices: Array<string> = connection.getPairedDevices();
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getPairState11+

getPairState(deviceId: string): BondState

Obtains the Bluetooth pairing state.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

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

Return value

TypeDescription
BondStateBluetooth pairing state obtained.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    let res: connection.BondState = connection.getPairState("XX:XX:XX:XX:XX:XX");
    console.info('getPairState: ' + res);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getProfileConnectionState

getProfileConnectionState(profileId?: ProfileId): ProfileConnectionState

Obtains the connection state of a Bluetooth profile. The ProfileId parameter is optional.

  • If ProfileId is specified, the connection state of the specified profile is returned.
  • If no ProfileId is specified, STATE_CONNECTED is returned by any connected profile. If no profile is connected, STATE_DISCONNECTED is returned.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
profileIdProfileIdNoID of the target profile, for example, PROFILE_A2DP_SOURCE.

Return value

TypeDescription
ProfileConnectionStateProfile connection state obtained.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Invalid parameter. Possible causes: 1. Incorrect parameter types.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900004Profile not supported.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
import { constant } from '@kit.ConnectivityKit';
try {
    let result: connection.ProfileConnectionState = connection.getProfileConnectionState(constant.ProfileId.PROFILE_A2DP_SOURCE);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.setDevicePairingConfirmation

setDevicePairingConfirmation(deviceId: string, accept: boolean): void

Sets the device pairing confirmation.

Required permissions: ohos.permission.ACCESS_BLUETOOTH and ohos.permission.MANAGE_BLUETOOTH (available only for system applications)

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
deviceIdstringYesAddress of the peer 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.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
// Subscribe to the pinRequired event and configure the pairing confirmation after receiving a pairing request from the peer device.
function onReceivePinRequiredEvent(data: connection.PinRequiredParam) { // data is the input parameter for the pairing request.
    console.info('pin required  = '+ JSON.stringify(data));
    connection.setDevicePairingConfirmation(data.deviceId, true);
}
try {
    connection.on('pinRequired', onReceivePinRequiredEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.setDevicePinCode

setDevicePinCode(deviceId: string, code: string, callback: AsyncCallback<void>): void

Sets the PIN for the device when PinType is PIN_TYPE_ENTER_PIN_CODE or PIN_TYPE_PIN_16_DIGITS. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
deviceIdstringYesMAC address of the peer device, for example, XX:XX:XX:XX:XX:XX.
codestringYesPIN to set.
callbackAsyncCallback<void>YesCallback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
// callback
try {
    connection.setDevicePinCode('11:22:33:44:55:66', '12345', (err: BusinessError) => {
        console.info('setDevicePinCode,device name err:' + JSON.stringify(err));
    });
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.setDevicePinCode

setDevicePinCode(deviceId: string, code: string): Promise<void>

Sets the PIN for the device when PinType is PIN_TYPE_ENTER_PIN_CODE or PIN_TYPE_PIN_16_DIGITS. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
deviceIdstringYesMAC address of the peer device, for example, XX:XX:XX:XX:XX:XX.
codestringYesPIN to set.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
// promise
try {
    connection.setDevicePinCode('11:22:33:44:55:66', '12345').then(() => {
        console.info('setDevicePinCode');
    }, (error: BusinessError) => {
        console.info('setDevicePinCode: errCode:' + error.code + ',errMessage' + error.message);
    })

} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.setLocalName(deprecated)

setLocalName(name: string): void

Sets the name of the local Bluetooth device.

NOTE
This API is supported since API version 10 and deprecated since API version 12. No substitute is provided.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

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

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    connection.setLocalName('device_name');
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.setBluetoothScanMode

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

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

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
modeScanModeYesBluetooth scan mode to set. If the scan times out (duration is not 0) when the scan mode is SCAN_MODE_GENERAL_DISCOVERABLE, the scan mode will be reset to SCAN_MODE_CONNECTABLE.
durationnumberYesDuration (in seconds) in which the device can be discovered. The value 0 indicates unlimited time.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    // The device can be discovered and connected only when the discoverable and connectable mode is used.
    connection.setBluetoothScanMode(connection.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 100);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getBluetoothScanMode

getBluetoothScanMode(): ScanMode

Obtains the Bluetooth scan mode.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

TypeDescription
ScanModeBluetooth scan mode obtained.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    let scanMode: connection.ScanMode = connection.getBluetoothScanMode();
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.startBluetoothDiscovery

startBluetoothDiscovery(): void

Starts to discover Bluetooth devices.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
function onReceiveEvent(data: Array<string>) {
    console.info('data length' + data.length);
}
try {
    connection.on('bluetoothDeviceFind', onReceiveEvent);
    connection.startBluetoothDiscovery();
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.stopBluetoothDiscovery

stopBluetoothDiscovery(): void

Stops discovering Bluetooth devices.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    connection.stopBluetoothDiscovery();
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.isBluetoothDiscovering11+

isBluetoothDiscovering(): boolean

Checks whether Bluetooth discovery is enabled.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Return value

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

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
try {
    let res: boolean = connection.isBluetoothDiscovering();
    console.info('isBluetoothDiscovering: ' + res);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.setRemoteDeviceName12+

setRemoteDeviceName(deviceId: string, name: string): Promise<void>

Sets the name of a remote Bluetooth device. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
deviceIdstringYesMAC address of the peer device, for example, XX:XX:XX:XX:XX:XX.
namestringYesName of the peer device to set. The name cannot exceed 64 bytes.

Return value

TypeDescription
Promise<void>Promise used to return the device name set. If the operation fails, an error code is returned.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
2900001Service stopped.
2900003Bluetooth disabled.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
// promise
try {
    connection.setRemoteDeviceName('11:22:33:44:55:66', 'RemoteDeviceName').then(() => {
        console.info('setRemoteDeviceName success');
    }, (error: BusinessError) => {
        console.error('setRemoteDeviceName: errCode:' + error.code + ',errMessage' + error.message);
    })

} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getRemoteDeviceBatteryInfo12+

getRemoteDeviceBatteryInfo(deviceId: string): Promise<BatteryInfo>

obtains the battery information of a remote Bluetooth device. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
deviceIdstringYesMAC address of the peer device, for example, 11:22:33:AA:BB:FF.

Return value

TypeDescription
Promise<BatteryInfo>Promise used to return the battery information obtained.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
2900001Service stopped.
2900003Bluetooth disabled.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
// promise
try {
    connection.getRemoteDeviceBatteryInfo('11:22:33:AA:BB:FF').then((data: connection.BatteryInfo) => {
        console.info('getRemoteDeviceBatteryInfo success, DeviceType:' + JSON.stringify(data));
    });
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.on('batteryChange')12+

on(type: 'batteryChange', callback: Callback<BatteryInfo>): void

Subscribes to the changes in the battery information of a remote Bluetooth device. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is 'batteryChange', which indicates the change in battery information of a remote Bluetooth device.
callbackCallback<BatteryInfo>YesCallback used to return the battery information.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
let onReceiveEvent: (data: connection.BatteryInfo) => void = (data: connection.BatteryInfo) => {
    console.info('BatteryInfo = '+ JSON.stringify(data));
}
try {
    connection.on('batteryChange', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.off('batteryChange')12+

off(type: 'batteryChange', callback?: Callback<BatteryInfo>): void

Unsubscribes from the changes in the battery information of a remote Bluetooth device.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is 'batteryChange', which indicates the change in battery information of a remote Bluetooth device.
callbackCallback<BatteryInfo>NoCallback to unregister.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
let onReceiveEvent: (data: connection.BatteryInfo) => void = (data: connection.BatteryInfo) => {
    console.info('BatteryInfo = '+ JSON.stringify(data));
}
try {
    connection.on('batteryChange', onReceiveEvent);
    connection.off('batteryChange', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.on('bluetoothDeviceFind')

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

Subscribes to the Bluetooth device discovered. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is bluetoothDeviceFind, which indicates an event of discovering a Bluetooth device.
callbackCallback<Array<string>>YesCallback used to return the discovered devices. You need to implement this callback. For security purposes, the device addresses are random MAC addresses. The random MAC address remains unchanged after a device is paired successfully. It changes when the paired device is unpaired and scanned again or the Bluetooth service is turned off.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
function onReceiveEvent(data: Array<string>) { // data is an array of Bluetooth device addresses.
    console.info('bluetooth device find = '+ JSON.stringify(data));
}
try {
    connection.on('bluetoothDeviceFind', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.off('bluetoothDeviceFind')

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

Unsubscribes from the Bluetooth device discovered.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is bluetoothDeviceFind, which indicates an event of discovering a Bluetooth device.
callbackCallback<Array<string>>NoCallback to unregister. If this parameter is not set, this API unregisters all callbacks for the specified type.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
801Capability not supported.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
function onReceiveEvent(data: Array<string>) {
    console.info('bluetooth device find = '+ JSON.stringify(data));
}
try {
    connection.on('bluetoothDeviceFind', onReceiveEvent);
    connection.off('bluetoothDeviceFind', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.on('bondStateChange')

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

Subscribes to Bluetooth pairing state changes. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

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

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
function onReceiveEvent(data: connection.BondStateParam) { // data, as the input parameter of the callback, indicates the pairing state.
    console.info('pair state = '+ JSON.stringify(data));
}
try {
    connection.on('bondStateChange', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.off('bondStateChange')

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

Unsubscribes from Bluetooth pairing state changes.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is bondStateChange, which indicates a Bluetooth pairing state change event.
callbackCallback<BondStateParam>NoCallback to unregister. If this parameter is not set, this API unregisters all callbacks for the specified type.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
function onReceiveEvent(data: connection.BondStateParam) {
    console.info('bond state = '+ JSON.stringify(data));
}
try {
    connection.on('bondStateChange', onReceiveEvent);
    connection.off('bondStateChange', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.on('pinRequired')

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

Subscribes to the pairing request events of the remote Bluetooth device. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

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

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
function onReceiveEvent(data: connection.PinRequiredParam) { // data is the pairing request parameter.
    console.info('pin required = '+ JSON.stringify(data));
}
try {
    connection.on('pinRequired', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.off('pinRequired')

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

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

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value pinRequired indicates a pairing request event.
callbackCallback<PinRequiredParam>NoCallback to unregister. The input parameter is the pairing request parameter. If this parameter is not set, this API unregisters all callbacks for the specified type.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
function onReceiveEvent(data: connection.PinRequiredParam) {
    console.info('pin required = '+ JSON.stringify(data));
}
try {
    connection.on('pinRequired', onReceiveEvent);
    connection.off('pinRequired', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.on('discoveryResult')18+

on(type: 'discoveryResult', callback: Callback<Array<DiscoveryResult>>): void

Subscribes to the Bluetooth device discovered. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is discoveryResult, which indicates information about the Bluetooth devices discovered.
callbackCallback<Array<DiscoveryResult>>YesCallback used to return the discovered devices. You need to implement this callback.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
let onReceiveEvent: (data: Array<connection.DiscoveryResult>) => void = (data: Array<connection.DiscoveryResult>) => { // data is an array of Bluetooth devices discovered.
    console.info('bluetooth device find = '+ JSON.stringify(data));
}
try {
    connection.on('discoveryResult', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.off('discoveryResult')18+

off(type: 'discoveryResult', callback?: Callback<Array<DiscoveryResult>>): void

Unsubscribes from the Bluetooth device discovered.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is discoveryResult, which indicates information about the Bluetooth devices discovered.
callbackCallback<Array<DiscoveryResult>>NoCallback to unregister. If this parameter is not set, this API unregisters all callbacks for the specified type.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
201Permission denied.
801Capability not supported.
2900099Operation failed.

Example

import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
let onReceiveEvent: (data: Array<connection.DiscoveryResult>) => void = (data: Array<connection.DiscoveryResult>) => { // data is an array of Bluetooth devices discovered.
    console.info('bluetooth device find = '+ JSON.stringify(data));
}
try {
    connection.on('discoveryResult', onReceiveEvent);
    connection.off('discoveryResult', onReceiveEvent);
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.getLastConnectionTime15+

getLastConnectionTime(deviceId: string): Promise<number>

Obtains the timestamp of the most recent connection to the peer device. This API uses a promise to return the result.

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
deviceIdstringYesMAC address of the peer device, for example, XX:XX:XX:XX:XX:XX.

Return value

TypeDescription
Promise<number>Promise used to return the result, which is the timestamp of the most recent connection to the peer device.

Error codes

For details about the error codes, see Bluetooth Error Codes.

IDError Message
401Invalid parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Operation failed.

Example

import { connection } from '@kit.ConnectivityKit';
// promise
try {
    connection.getLastConnectionTime('11:22:33:44:55:66').then((time: number) => {
        console.info('connectionTime: ${time}');
    });
} catch (err) {
    console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}

connection.connectAllowedProfiles16+

connectAllowedProfiles(deviceId: string, callback: AsyncCallback<void>): void

Connects all profiles allowed for a peer device. This API uses an asynchronous callback to return the result.
Call pairDevice to initiate pairing first. This API can be called only once within 30 seconds after each pairing is initiated.
Recommended usage: Subscribe to UUID_VALUE common event callbacks so that the application can receive a callback upon successful pairing of a Bluetooth device. You are advised to call connectAllowedProfiles in this callback.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

NameTypeMandatoryDescription
deviceIdstringYesAddress of the peer device, for example, XX:XX:XX:XX:XX.
callbackAsyncCallback<void>YesCallback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Universal Error Codes and Bluetooth Error Codes.

IDError Message
201Permission denied.
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Operation failed.

Example

import { commonEventManager, AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
import { connection } from '@kit.ConnectivityKit';
// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription.
let subscriber: commonEventManager.CommonEventSubscriber;
// Subscriber information.
let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
  events: ["usual.event.bluetooth.remotedevice.UUID_VALUE"]
};
// Subscribe to common event callbacks.
function SubscribeCB(err: BusinessError, data: commonEventManager.CommonEventData) {
  if (err) {
    console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
  } else {
    console.info(`Succeeded in subscribing, data is ` + JSON.stringify(data));
    // Before calling connectAllowedProfiles, ensure that the application has received the UUID_VALUE common event.
    try {
        connection.connectAllowedProfiles('68:13:24:79:4C:8C', (err: BusinessError) => {
            if (err) {
                console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
                return;
            }
            console.info('connectAllowedProfiles, err: ' + JSON.stringify(err));
        });
    } catch (err) {
        console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
    }
  }
}
// Callback for subscriber creation.
function createCB(err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) {
  if(!err) {
    console.info(`Succeeded in creating subscriber.`);
    subscriber = commonEventSubscriber;
    // Subscribe to common events.
    try {
      commonEventManager.subscribe(subscriber, SubscribeCB);
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
    }
  } else {
    console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
  }
}

// Create a subscriber and subscribe to the common event callbacks.
try {
  commonEventManager.createSubscriber(subscribeInfo, createCB);
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
}

connection.connectAllowedProfiles16+

connectAllowedProfiles(deviceId: string): Promise<void>

Connects all profiles allowed for a peer device. This API uses a promise to return the result.
Call pairDevice to initiate pairing first. This API can be called only once within 30 seconds after each pairing is initiated.
Recommended usage: Subscribe to UUID_VALUE common event callbacks so that the application can receive a callback upon successful pairing of a Bluetooth device. You are advised to call connectAllowedProfiles in this callback.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.Communication.Bluetooth.Core

Parameters

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

Return value

TypeDescription
Promise<void>Promise used to return the result.

Error codes

For details about the error codes, see Universal Error Codes and Bluetooth Error Codes.

IDError Message
201Permission denied.
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed.
801Capability not supported.
2900001Service stopped.
2900003Bluetooth disabled.
2900099Operation failed.

Example

import { commonEventManager, AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
import { connection } from '@kit.ConnectivityKit';
// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription.
let subscriber: commonEventManager.CommonEventSubscriber;
// Subscriber information.
let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
  events: ["usual.event.bluetooth.remotedevice.UUID_VALUE"]
};
// Subscribe to common event callbacks.
function SubscribeCB(err: BusinessError, data: commonEventManager.CommonEventData) {
  if (err) {
    console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
  } else {
    console.info(`Succeeded in subscribing, data is ` + JSON.stringify(data));
    // Before calling connectAllowedProfiles, ensure that the application has received the UUID_VALUE common event.
    try {
        connection.connectAllowedProfiles('68:13:24:79:4C:8C').then(() => {
            console.info('connectAllowedProfiles');
        }, (err: BusinessError) => {
            console.error('connectAllowedProfiles:errCode' + err.code + ', errMessage: ' + err.message);
        });
    } catch (err) {
        console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
    }
  }
}
// Callback for subscriber creation.
function createCB(err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) {
  if(!err) {
    console.info(`Succeeded in creating subscriber.`);
    subscriber = commonEventSubscriber;
    // Subscribe to common events.
    try {
      commonEventManager.subscribe(subscriber, SubscribeCB);
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`);
    }
  } else {
    console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
  }
}

// Create a subscriber and subscribe to the common event callbacks.
try {
  commonEventManager.createSubscriber(subscribeInfo, createCB);
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
}

BondStateParam

Represents the pairing state parameters.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesNoID of the device to pair.
stateBondStateYesNoState of the device.
cause12+UnbondCauseYesNoCause of the pairing failure.

PinRequiredParam

Represents the pairing request parameters.

System capability: SystemCapability.Communication.Bluetooth.Core

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

DeviceClass

Represents the class of a Bluetooth device.

System capability: SystemCapability.Communication.Bluetooth.Core

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

BatteryInfo12+

Represents the battery information.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
batteryLevelnumberYesNoBattery level of the peer device. If the value is -1, there is no battery information.
leftEarBatteryLevelnumberYesNoBattery level of the left earphone. If the value is -1, there is no battery information.
leftEarChargeStateDeviceChargeStateYesNoCharging state of the left earphone.
rightEarBatteryLevelnumberYesNoBattery level of the right earphone. If the value is -1, there is no battery information.
rightEarChargeStateDeviceChargeStateYesNoCharging state of the right earphone.
boxBatteryLevelnumberYesNoBattery level of the earbud compartment. If the value is -1, there is no battery information.
boxChargeStateDeviceChargeStateYesNoCharging state of the earbud compartment.

BluetoothTransport

Enumerates the device types. The default device type is TRANSPORT_BR_EDR.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
TRANSPORT_BR_EDR0Classic Bluetooth (BR/EDR) device.
TRANSPORT_LE1BLE device.

ScanMode

Enumerates the scan modes.

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.

BondState

Enumerates the pairing states.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
BOND_STATE_INVALID0Invalid pairing.
BOND_STATE_BONDING1Pairing.
BOND_STATE_BONDED2Paired.

UnbondCause12+

Enumerates the possible causes of a pairing failure.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
USER_REMOVED0The user proactively removes the device.
REMOTE_DEVICE_DOWN1The peer device is shut down.
AUTH_FAILURE2The PIN is incorrect.
AUTH_REJECTED3The peer device authentication is rejected.
INTERNAL_ERROR4Internal error.

DeviceChargeState12+

Enumerates the charging states.

System capability: SystemCapability.Communication.Bluetooth.Core

NameValueDescription
DEVICE_NORMAL_CHARGE_NOT_CHARGED0The device is not charged and does not support supercharging.
DEVICE_NORMAL_CHARGE_IN_CHARGING1The device is being charged and does not support supercharging.
DEVICE_SUPER_CHARGE_NOT_CHARGED2The device is not charged and supports supercharging.
DEVICE_SUPER_CHARGE_IN_CHARGING3The device is being charged and supports supercharging.

DiscoveryResult18+

Represents information about the discovered device.

System capability: SystemCapability.Communication.Bluetooth.Core

NameTypeReadableWritableDescription
deviceIdstringYesNoID of the discovered device.
rssinumberYesNoRSSI of the discovered device.
deviceNamestringYesNoName of the discovered device.
deviceClassDeviceClassYesNoBluetooth class of the discovered device.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Connectivity Kit (Short-Range Communication Service)

harmony 鸿蒙Bluetooth

harmony 鸿蒙Wifi

harmony 鸿蒙Bluetooth Error Codes

harmony 鸿蒙NFC Error Codes

harmony 鸿蒙SecureElement Error Codes

harmony 鸿蒙Wi-Fi Error Codes

harmony 鸿蒙@ohos.bluetooth.a2dp (Bluetooth A2DP Module) (System API)

harmony 鸿蒙@ohos.bluetooth.a2dp (Bluetooth A2DP Module)

harmony 鸿蒙@ohos.bluetooth.access (Bluetooth Access Module) (System API)

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