HarmonyOS鸿蒙Next中查询手写笔与设备的配对状态
HarmonyOS鸿蒙Next中查询手写笔与设备的配对状态 请教各位大佬,纯血鸿蒙如何实现以下功能:
1.手机和手写笔配对后,app是否可以检测该到事件?
2.app启动后,如何检测手机是否已经和手写笔配对?
开发者您好,手写笔设备一般通过蓝牙或者星闪与手机设备进行配对:
-
如果您希望在手机和手写笔配对后,有办法感知这个配对事件,可参考如下方法:
-
若为蓝牙设备:可在应用启动时,通过connection.on(‘bondStateChange’)监听设备配对状态变化,如下:
import { connection, constant } from '@kit.ConnectivityKit'; connection.on('bondStateChange', (data: connection.BondStateParam) => { let deviceId = data.deviceId; // 配对中的对端设备地址 let bondState = data.state; // 配对的状态,BOND_STATE_BONDED表示已经配对完成 let cause = data.cause; // 配对失败的原因 // 判断是否配对成功 if (bondState == connection.BondState.BOND_STATE_BONDED) { // 如果需要判断是否为手写笔设备,可通过connection.getRemoteDeviceClass,传入deviceId来查询对端设备类型 let deviceClass = connection.getRemoteDeviceClass(deviceId); if (deviceClass.majorMinorClass === constant.MajorMinorClass.PERIPHERAL_DIGITAL_PEN) { // 表示外设数码笔设备 console.info('与手写笔设备配对成功'); } } else { console.info(`未找到配对手写笔设备:${cause}`) } }) -
若为星闪设备:可在应用启动时通过manager.on(‘pairingStateChange’)订阅配对请求事件:
import { manager, constant as nearConstant, remoteDevice } from '@kit.NearLinkKit'; import { BusinessError } from '@kit.BasicServicesKit'; manager.on('pairingStateChange', (data: manager.PairingStateParam) => { let address = data.address // 设备地址 let preState = data.preState; // 本次上报之前的配对状态 let state = data.state; // 当前配对状态 let reason = data.reason; // 原因值 if (state === nearConstant.PairingState.PAIRING_STATE_PAIRED) { let device: remoteDevice.RemoteDevice | undefined = undefined; try { device = remoteDevice.createRemoteDevice(address); } catch (err) { console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } if (device) { let deviceClass = device.getDeviceClass(); if (deviceClass === nearConstant.DeviceClass.DEVICE_STYLUS) { console.info('已成功与手写笔设备配对'); } } } });
-
-
如果您需要在app启动时,判断当前设备是否已经与手写笔设备完成配对,可参考如下方式:
-
如果为蓝牙设备,可以通过connection.getPairedDevices获取当前已配对的蓝牙设备集合,从中判断是否存在已经配对的手写笔设备:
import { connection, constant } from '@kit.ConnectivityKit'; let deviceIds = connection.getPairedDevices(); for (let deviceId of deviceIds) { let deviceClass = connection.getRemoteDeviceClass(deviceId); if (deviceClass.majorMinorClass === constant.MajorMinorClass.PERIPHERAL_DIGITAL_PEN) { // 表示外设数码笔设备 console.info('已找到配对手写笔设备'); } }如果您已经提前持久化之前完成配对的手写笔设备信息,也可以直接通过保存的信息来获取并判断
-
如果为星闪设备,可以通过manager.getPairedDevices获取与当前设备配对的设备地址集合,从中判断是否存在已经配对的手写笔设备:
import { manager, constant as nearConstant, remoteDevice } from '@kit.NearLinkKit'; import { BusinessError } from '@kit.BasicServicesKit'; let addressList = manager.getPairedDevices(); for (let add of addressList) { let device: remoteDevice.RemoteDevice | undefined = undefined; try { device = remoteDevice.createRemoteDevice(add); } catch (err) { console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } if (device) { let deviceClass = device.getDeviceClass(); if (deviceClass === nearConstant.DeviceClass.DEVICE_STYLUS) { console.info('已成功与手写笔设备配对'); } } }
-
可参考文档:
- [@ohos.bluetooth.connection (蓝牙connection模块)](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-bluetooth-connection)
- manager(星闪开关能力)
- remoteDevice(对端设备的连接能力)
更多关于HarmonyOS鸿蒙Next中查询手写笔与设备的配对状态的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/pen-introduction

这里有个官方的demo: https://developer.huawei.com/consumer/cn/codelabsPortal/carddetails/tutorials_PenKit-Next-Easy
import { HandwriteController, HandwriteComponent, PenHspInfo, PenType } from '@kit.Penkit';
@Entry
@Component
struct HandWriteDemoComp {
controller: HandwriteController = new HandwriteController();
// 根据应用存储规则,获取到手写文件保存的路径,此处仅为实例参考
initPath: string = this.getUIContext().getHostContext()?.filesDir + '/aa';
penWidth: number = 5;
ballpointPenWidth: number = 6;
aboutToAppear() {
// 加载时设置保存动作完成后的回调。
this.controller.onLoad(this.callback);
}
// 手写文件内容加载完毕渲染上屏后的回调,通知接入用户,可在此处进行自定义行为
callback = () => {
// 自定义行为,例如文件加载完毕后展示用户操作指导
}
build() {
Row() {
Stack({ alignContent: Alignment.TopStart }) {
HandwriteComponent({
handwriteController: this.controller,
defaultPenType: PenType.PEN, // 可选属性,默认笔刷
defaultPenInfo: [{ penType: PenType.PEN, penWidth: this.penWidth },
{ penType: PenType.BALLPOINT_PEN, penWidth: this.ballpointPenWidth }] as PenHspInfo[], //可选属性,各笔刷的默认宽度
widthRatio: 1, //可选属性,自定义画布大小,宽度占比(0-1)。
heightRatio: 1, //可选属性,自定义画布大小,高度占比(0-1)。
onInit: () => {
// 画布初始化完成时的回调。此时可以调用接口加载和显示笔记内容
this.controller?.load(this.initPath);
},
onScale: (scale: number) => {
// 画布缩放时的回调方法,将返回当前手写控件的缩放比例,可在此处进行自定义行为。
}
})
Button("save")
.onClick(async () => {
// 需根据应用存储规则,获取到手写文件保存的路径,此处仅为实例参考。
const path = this.getUIContext().getHostContext()?.filesDir + '/aa';
await this.controller?.save(path).then().catch((error: Error) => {
console.info("err:" + error);
})
// 获取缩略图。
this.controller.getThumbnail(this.controller?.getContentRange())?.then((pixelMap: PixelMap) => {
if (pixelMap) {
pixelMap.release()
console.info('getThumbnail success')
}
})
})
}
.width('100%')
}
.height('100%')
}
}
应该监听不到。不过可以监听手写笔点击事件。
在 HarmonyOS Next 中,可通过分布式设备管理或蓝牙接口查询/监听手写笔配对状态。
1. 监听配对事件
注册 deviceManager.on('deviceStateChange', callback) 可捕获设备上线/离线,过滤设备类型为手写笔(通常deviceType为 'stylus' 或通过蓝牙 ClassOfDevice 判定)即可。
2. 查询当前配对状态
用 deviceManager.getTrustedDeviceList() 获取已授信设备列表,遍历并检查 deviceType 是否为手写笔;或通过蓝牙 bluetooth.getPairedDevices() 获取配对设备,再按设备类别 getClassOfDevice 判断是否为手写笔(Peripheral Major Class 为 Peripheral,Minor 为 Stylus)。
关键代码(基于分布式设备管理):
import deviceManager from '@ohos.distributedDeviceManager';
import { BusinessError } from '@kit.BasicServicesKit';
try {
let dmInstance = deviceManager.createDeviceManager('com.example.app');
// 监听状态变化
dmInstance.on('deviceStateChange', (data) => {
if (data.action === deviceManager.DeviceStateChangeAction.ONLINE && data.device.deviceType === 'stylus') {
console.info('手写笔已配对上线');
}
});
// 查询已配对设备
let trustedList = dmInstance.getTrustedDeviceListSync();
let stylusConnected = trustedList.some(device => device.deviceType === 'stylus');
console.info('当前手写笔配对状态:', stylusConnected);
} catch (err) {
let error = err as BusinessError;
console.error('操作失败,错误码:', error.code);
}
若未使用分布式能力,可用 @ohos.bluetooth 类似实现。


