输入设备管理提供设备热插拔监听、查询指定设备的键盘类型等能力。使用场景例如:当用户需要输入文本时,输入法会根据当前是否插入了物理键盘来决定是否弹出虚拟键盘,开发者可以通过监听设备热插拔判断是否有物理键盘插入。
- import { inputDevice } from '@kit.InputKit';
输入设备管理常用接口如下表所示,接口详细介绍请参考@ohos.multimodalInput.inputDevice (输入设备)。
| 接口名称 | 描述 |
|---|---|
| getDeviceList(): Promise<Array<number>> | 获取所有输入设备的ID列表。 |
| getKeyboardType(deviceId: number): Promise<KeyboardType> | 获取输入设备的键盘类型。 |
| on(type: 'change', listener: Callback<DeviceListener>): void | 注册监听输入设备的热插拔事件。 |
| off(type: 'change', listener?: Callback<DeviceListener>): void | 取消监听输入设备的热插拔事件。 |
当用户需要输入文本时,输入法会根据当前是否插入了物理键盘来决定是否弹出虚拟键盘,开发者可以通过监听设备热插拔,判断是否有物理键盘插入。
- import { inputDevice } from '@kit.InputKit';
- import { hilog } from '@kit.PerformanceAnalysisKit';
-
- const DOMAIN = 0x0000;
-
- @Entry
- @Component
- struct Index {
- @State isPhysicalKeyboardExist: boolean = false;
- @State message: string = "Click to obtain the device list and monitor device hot-plug events";
- keyboards: Map<number, inputDevice.KeyboardType> = new Map();
-
- // ...
-
- build() {
- RelativeContainer() {
- Column() {
- // ...
-
- Text(this.message)
- .onClick(() => {
- try {
- // 1.获取设备列表,判断是否有物理键盘连接
- inputDevice.getDeviceList().then(data => {
- for (let i = 0; i < data.length; ++i) {
- inputDevice.getKeyboardType(data[i]).then(type => {
- if (type === inputDevice.KeyboardType.ALPHABETIC_KEYBOARD) {
- // 物理键盘已连接
- this.isPhysicalKeyboardExist = true;
- this.keyboards.set(data[i], type);
- }
- });
- }
- });
- // 2.监听设备热插拔
- inputDevice.on("change", (data) => {
- hilog.info(DOMAIN, 'InputDevice', `Device event info: %{public}s`, JSON.stringify(data));
- inputDevice.getKeyboardType(data.deviceId).then((type) => {
- hilog.info(DOMAIN, 'InputDevice', 'The keyboard type is: %{public}d', type);
- if (type === inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type === 'add') {
- // 物理键盘已插入
- this.isPhysicalKeyboardExist = true;
- this.keyboards.set(data.deviceId, type);
- }
- });
- if (this.keyboards.get(data.deviceId) === inputDevice.KeyboardType.ALPHABETIC_KEYBOARD &&
- data.type === 'remove') {
- // 物理键盘已拔出
- this.isPhysicalKeyboardExist = false;
- this.keyboards.delete(data.deviceId);
- }
- });
- this.message = "Device monitoring enabled successfully"
- } catch (error) {
- hilog.error(DOMAIN, 'InputDevice', `Execute failed, error: %{public}s`,
- JSON.stringify(error, ["code", "message"]));
- this.message = `Failed to enable device monitoring. Click to retry. Error message:${JSON.stringify(error,
- ["code", "message"])}`
- }
- })
- // ...
- }
- // ...
- }
- }
- }
合作咨询
我们的专家服务团队将竭诚为您提供专业的合作咨询服务
解决方案
精准高效的一站式服务支持,助力开发者商业成功