1/* 2 * Copyright (c) 2023 Fujian Newland Auto-ID Tech.Co.,Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15import { logger, formatJson } from '@ohos/common' 16import inputMonitor from '@ohos.multimodalInput.inputMonitor' 17import inputEventClient from '@ohos.multimodalInput.inputEventClient' 18 19const TAG: string = '[Sample_InputEventUtil]' 20 21interface KeyEventType{ 22 KeyEvent: inputEventClient.KeyEvent 23} 24 25/** 26 * 注入返回按键事件 27 */ 28export function injectBackEvent(): void { 29 try { 30 let backKeyDown: KeyEventType = { 31 KeyEvent:{ 32 isPressed: true, 33 keyCode: 2, 34 keyDownDuration: 0, 35 isIntercepted: false 36 } 37 }; 38 inputEventClient.injectEvent(backKeyDown); 39 40 let backKeyUp: KeyEventType = { 41 KeyEvent: { 42 isPressed: false, 43 keyCode: 2, 44 keyDownDuration: 0, 45 isIntercepted: false 46 } 47 }; 48 inputEventClient.injectEvent(backKeyUp); 49 } catch (error) { 50 console.log(`Failed to inject KeyEvent, error: ${JSON.stringify(error, [`code`, `message`])}`) 51 } 52} 53 54class TouchManagerUtil { 55 private callback: Function | null = null; 56 57 public registerTouch(callback: Function): void { 58 logger.info(`${TAG} registerTouch`) 59 try { 60 this.callback = callback 61 inputMonitor.on('touch', (touchEvent: TouchEvent): Boolean => this.onTouchCallback(touchEvent)); 62 } catch (error) { 63 logger.error(`${TAG} register touch on failed, error: ${JSON.stringify(error, [`code`, `message`])}`) 64 } 65 } 66 67 public unregisterTouch(): void { 68 try { 69 inputMonitor.off('touch') 70 this.callback = null 71 logger.info(`${TAG} Monitor off success`) 72 } catch (error) { 73 logger.error(`${TAG} unregister touch execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`) 74 } 75 76 } 77 78 private onTouchCallback(event: TouchEvent) { 79 logger.info(`${TAG} onTouchCallback event: ${JSON.stringify(event)}`) 80 if (this.callback && this.callback !== null && this.callback !== undefined) { 81 this.callback(formatJson(JSON.stringify(event))) 82 } 83 return false 84 } 85} 86 87export default new TouchManagerUtil()