openharmony 鸿蒙 js-apis-proxyChannelManager

2026-08-25 浏览 (1)

@ohos.distributedsched.proxyChannelManager (Proxy Channel Management)

DSoftBus provides stable and reliable underlying channels for cross-device communication. This module is developed based on DSoftBus. It supports efficient data exchange between phones and wearables, providing users with a seamless device interconnection experience. During collaboration between the phone application and watch application, if the phone application is not running in the foreground, its downlink messages are forwarded to the notification server and then sent to the watch through the proxy module. The core functions of this module include proxy channel management, data route management, application state awareness and wakeup, and link state monitoring.

  • Proxy channel management: Manages bidirectional data channels established between phones and wearables via the Bluetooth Basic Rate (BR) protocol.

  • Data route management: Accurately forwards data of wearables based on the specified service UUID.

  • Application state awareness and wakeup: After a proxy channel is enabled, dynamically analyzes and wakes up the corresponding application process on the phone after receiving data sent by the wearable.

  • Link state monitoring: Monitors the channel connection state in real time through callback.

NOTE

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

Model restriction: This API can be used only in the stage model.

Modules to Import

import { proxyChannelManager } from '@kit.DistributedServiceKit';

Instructions

Before calling the APIs of this module, complete the following configurations:

  1. Apply for the ohos.permission.ACCESS_BLUETOOTH permission. For details about how to configure and apply for permissions, see Declaring Permissions and Requesting User Authorization.

  2. For application processes that need to be started by proxy, set the action field to action.ohos.pull.listener in the module.json5 file.

proxyChannelManager.openProxyChannel

openProxyChannel(channelInfo: ChannelInfo): Promise<number>

Opens a proxy channel. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.DistributedSched.AppCollaboration

Model restriction: This API can be used only in the stage model.

Parameters

NameTypeMandatoryDescription
channelInfoChannelInfoYesChannel information, including the MAC address and service UUID of the peer device.

Return value

TypeDescription
 Promise<number>Proxy channel ID. The value range is [1, 2147483647]. The lifecycle of channelId is the same as that of the proxy channel. If the proxy is not closed, the returned channelId is the same as that passed in the API.

Error codes

For details about the following error codes, see Proxy Channel Management Error Codes and Universal Error Codes.

IDError Message
201Permission denied.
801Capability not supported.[since 26]
32390001BR is disabled.
32390002Device not paired.
32390006Parameter error.
32390100Internal error.
32390101Call is restricted.
32390102Operation failed or Connection timed out.

Example

import { proxyChannelManager } from '@kit.DistributedServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Button ('Test')
        .onClick(() => {
          let channelInfo: proxyChannelManager.ChannelInfo = {
            linkType: proxyChannelManager.LinkType.LINK_BR,
            peerDevAddr: "xx:xx:xx:xx:xx:xx", // Bluetooth MAC address of the wearable
            peerUuid: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", // Service UUID of the peer device
          };
          // The following sample code uses try/catch as an example.
          try {
            proxyChannelManager.openProxyChannel(channelInfo)
              .then((channelId: number) => {
                // Obtain the channel ID.
              })
              .catch((error: BusinessError) => {
                console.error(`getErr: ${error.code} ${error.message}`);
              });
          } catch (err) {
            let error = err as BusinessError;
            console.error(`getErr: ${error.code} ${error.message}`);
            // If code:undefined message:"Cannot read property openProxyChannel of undefined" is displayed, this API is not supported in the current image.
          }
        })
    }
    .height('100%')
    .width('100%')
  }
}

proxyChannelManager.closeProxyChannel

closeProxyChannel(channelId: number): void

Closes a proxy channel that has been opened.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.DistributedSched.AppCollaboration

Model restriction: This API can be used only in the stage model.

Parameters

NameTypeMandatoryDescription
channelIdnumberYesChannel ID obtained when the proxy channel is opened.

Error codes

For details about the following error codes, see Proxy Channel Management Error Codes and Universal Error Codes.

IDError Message
201Permission denied.
801Capability not supported.[since 26]
32390004ChannelId is invalid or unavailable.
32390006Parameter error.
32390100Internal error.
32390101Call is restricted.

Example

import { proxyChannelManager } from '@kit.DistributedServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Button ('Test')
        .onClick(() => {
          // The following sample code uses try/catch as an example.
          try {
            proxyChannelManager.closeProxyChannel(1); // Assume that the channel ID is 1.
          } catch (err) {
            let error = err as BusinessError;
            console.error(`getErr: ${error.code} ${error.message}`);
            // If code:undefined message:"Cannot read property closeProxyChannel of undefined" is displayed, this API is not supported in the current image.
          }
        })
    }
    .height('100%')
    .width('100%')
  }
}

proxyChannelManager.sendData

sendData(channelId:number, data:ArrayBuffer):Promise<void>

Sends data to the peer end. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.DistributedSched.AppCollaboration

Model restriction: This API can be used only in the stage model.

Parameters

NameTypeMandatoryDescription
channelIdnumberYesChannel ID obtained when the proxy channel is opened.
dataArrayBufferYesByte message sent to the peer end. The maximum length is 4096 bytes.

Return value

TypeDescription
 Promise<void>Promise that returns no value.

Error codes

For details about the following error codes, see Proxy Channel Management Error Codes and Universal Error Codes.

IDError Message
201Permission denied.
801Capability not supported.[since 26]
32390004ChannelId is invalid or unavailable.
32390006Parameter error.
32390100Internal error.
32390101Call is restricted.
32390103Data too long.
32390104Send failed.

Example

import { proxyChannelManager } from '@kit.DistributedServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Button ('Test')
        .onClick(() => {
          const data = new ArrayBuffer(10); // Create an ArrayBuffer with a length of 10.
          try {
            proxyChannelManager.sendData(1, data) // Assume that the channel ID is 1.
              .then(() => {
              })
              .catch((error: BusinessError) => {
                console.error(`getErr: ${error.code} ${error.message}`);
              });
          } catch (err) {
            let error = err as BusinessError;
            console.error(`getErr: ${error.code} ${error.message}`);
          }
        })
    }
    .height('100%')
    .width('100%')
  }
}

proxyChannelManager.on('receiveData')

on(type: 'receiveData', channelId: number, callback: Callback<DataInfo>): void

Subscribes to data receiving events. This API returns the result asynchronously through a callback.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.DistributedSched.AppCollaboration

Model restriction: This API can be used only in the stage model.

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value receiveData indicates the data receiving event.
channelIdnumberYesChannel ID obtained when the proxy channel is opened.
callbackCallback<DataInfo>YesCallback used to return the received data. If the callback function is registered multiple times, only the last registered one takes effect.

Error codes

For details about the following error codes, see Proxy Channel Management Error Codes and Universal Error Codes.

IDError Message
201Permission denied.
32390004ChannelId is invalid or unavailable.
32390006Parameter error.
32390100Internal error.
32390101Call is restricted.

Example

import { proxyChannelManager } from '@kit.DistributedServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Button ('Test')
        .onClick(() => {
          const receiveDataCallback = (dataInfo: proxyChannelManager.DataInfo) => {
          };
          try {
            proxyChannelManager.on('receiveData', 1, receiveDataCallback); // Assume that the channel ID is 1.
          } catch (err) {
            let error = err as BusinessError;
            console.error(`register receiveData error: ${error.code} ${error.message}`);
          }
        })
    }
    .height('100%')
    .width('100%')
  }
}

proxyChannelManager.off('receiveData')

off(type: 'receiveData', channelId: number, callback?: Callback<DataInfo>): void

Unsubscribes from data receiving events.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.DistributedSched.AppCollaboration

Model restriction: This API can be used only in the stage model.

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value receiveData indicates the data receiving event.
channelIdnumberYesChannel ID obtained when the proxy channel is opened.
callbackCallback<DataInfo>NoRegistered callback, If the value is empty, undefined, or null, all callbacks of data receiving events are unregistered. If the value is not empty, the last registered callback is used.

Error codes

For details about the following error codes, see Proxy Channel Management Error Codes and Universal Error Codes.

IDError Message
201Permission denied.
32390004ChannelId is invalid or unavailable.
32390006Parameter error.
32390100Internal error.
32390101Call is restricted.

Example

import { proxyChannelManager } from '@kit.DistributedServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Button ('Test')
        .onClick(() => {
          try {
            proxyChannelManager.off('receiveData', 1); // Assume that the channel ID is 1.
          } catch (err) {
            let error = err as BusinessError;
            console.error(`getErr: ${error.code} ${error.message}`);
          }
        })
    }
    .height('100%')
    .width('100%')
  }
}

proxyChannelManager.on('channelStateChange')

on(type: 'channelStateChange', channelId: number, callback: Callback<ChannelStateInfo>): void

Subscribes to channel state change events. This API returns the result asynchronously through a callback.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.DistributedSched.AppCollaboration

Model restriction: This API can be used only in the stage model.

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value channelStateChange indicates the channel state change event.
channelIdnumberYesChannel ID obtained when the proxy channel is opened.
callbackCallback<ChannelStateInfo>YesCallback used to return the received channel state. If the callback function is registered multiple times, only the last registered one takes effect.

Error codes

For details about the following error codes, see Proxy Channel Management Error Codes and Universal Error Codes.

IDError Message
201Permission denied.
32390004ChannelId is invalid or unavailable.
32390006Parameter error.
32390100Internal error.
32390101Call is restricted.

Example

import { proxyChannelManager } from '@kit.DistributedServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Button ('Test')
        .onClick(() => {
          const receiveStatusCallback = (channelStateInfo: proxyChannelManager.ChannelStateInfo) => {
          };
          try {
            proxyChannelManager.on ('channelStateChange', 1, receiveStatusCallback); // Assume that the channel ID is 1.
          } catch (err) {
            let error = err as BusinessError;
            console.error(`getErr: ${error.code} ${error.message}`);
          }
        })
    }
    .height('100%')
    .width('100%')
  }
}

proxyChannelManager.off('channelStateChange')

off(type: 'channelStateChange', channelId: number, callback?: Callback<ChannelStateInfo>): void

Unsubscribes from channel state change events.

Required permissions: ohos.permission.ACCESS_BLUETOOTH

System capability: SystemCapability.DistributedSched.AppCollaboration

Model restriction: This API can be used only in the stage model.

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value channelStateChange indicates the channel state change event.
channelIdnumberYesChannel ID obtained when the proxy channel is opened.
callbackCallback<ChannelStateInfo>NoRegistered callback, If the value is empty, undefined, or null, all callbacks of data receiving events are unregistered. If the value is not empty, the last registered callback is used.

Error codes

For details about the following error codes, see Proxy Channel Management Error Codes and Universal Error Codes.

IDError Message
201Permission denied.
32390004ChannelId is invalid or unavailable.
32390006Parameter error.
32390100Internal error.
32390101Call is restricted.

Example

import { proxyChannelManager } from '@kit.DistributedServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Button ('Test')
        .onClick(() => {
          try {
            proxyChannelManager.off('channelStateChange', 1); // Assume that the channel ID is 1.
          } catch (err) {
            let error = err as BusinessError;
            console.error(`getErr: ${error.code} ${error.message}`);
          }
        })
    }
    .height('100%')
    .width('100%')
  }
}

DataInfo

Represents the received data, including the channel ID and data.

System capability: SystemCapability.DistributedSched.AppCollaboration

NameTypeRead-OnlyOptionalDescription
channelIdnumberNoNoProxy channel ID.
dataArrayBufferNoNoReceived byte array.

ChannelInfo

Represents the proxy channel information, including the MAC address and service UUID of the peer device.

System capability: SystemCapability.DistributedSched.AppCollaboration

NameTypeRead-OnlyOptionalDescription
linkTypeLinkTypeNoNoLink type of the proxy channel.
peerDevAddrstringNoNoMAC address of the peer device.
peerUuidstringNoNoService UUID of the peer device.

ChannelStateInfo

Represents the connection state information of the proxy channel.

System capability: SystemCapability.DistributedSched.AppCollaboration

NameTypeRead-OnlyOptionalDescription
channelIdnumberNoNoProxy channel ID.
stateChannelStateNoNoConnection state of the proxy channel.

ChannelState

Enumerates the connection states of the proxy channel.

System capability: SystemCapability.DistributedSched.AppCollaboration

NameValueDescription
CHANNEL_WAIT_RESUME0The connection is disconnected, and the channel is unavailable.
CHANNEL_RESUME1The connection is restored, and the channel is available.
CHANNEL_EXCEPTION_SOFTWARE_FAILED2The channel is unavailable due to other software errors.
CHANNEL_BR_NO_PAIRED3The Bluetooth pairing relationship is deleted, and the channel is unavailable.

LinkType

Enumerates the link types.

System capability: SystemCapability.DistributedSched.AppCollaboration

NameValueDescription
LINK_BR0Bluetooth.

你可能感兴趣的鸿蒙文章

openharmony 鸿蒙 js-apis-distributedHardwareManager-sys

openharmony 鸿蒙 capi-oh-device-manager-err-code-h

openharmony 鸿蒙 js-apis-devicestatus-cooperate-sys

openharmony 鸿蒙 errorcode-link-enhance

openharmony 鸿蒙 errorcode-devicestatus

openharmony 鸿蒙 js-apis-distributedDeviceManager-sys

openharmony 鸿蒙 js-apis-distributedExtensionAbility

openharmony 鸿蒙 js-apis-link-enhance

openharmony 鸿蒙 errorcode-device-manager

openharmony 鸿蒙 Readme-EN

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