Android代码中发送Keycode按键

您所在的位置:网站首页 android10131 Android代码中发送Keycode按键

Android代码中发送Keycode按键

2024-07-13 03:14| 来源: 网络整理| 查看: 265

前言

有时候在代码中需要模拟一些用户操作的按键,例如TV 中遥控器的按键,一些测试脚本的编写。再比如android 手机中虚拟按键,以及悬浮窗中的返回功能,等等。都是模拟发送按键来操作。

这里介绍三种方法,来实现用代码模拟发送按键。目前我都是在系统中(有系统签名和shareuid)测试的。如果第三方app想要调用使用,不知权限是否够。

1.调用input 命令

使用过串口的都明白,如果需要debug 模拟按键,会使用 input keyevent 的方法。这个使用android runtime 模拟执行命令。值得一提的是,有些情况下有人想在代码里调用 adb shell xxx也可以用类似的方式:

try{ String keyCommand = "input keyevent " + KeyEvent.KEYCODE_1; Runtime runtime = Runtime.getRuntime(); Process proc = runtime.exec(keyCommand); } catch(IOException e){ } 2.在线程中使用Instrumentation

这个方法必须要在线程中执行才有效:

import android.app.Instrumentation; sendKeyCode(KeyEvent.KEYCODE_DPAD_UP); private void sendKeyCode(final int keyCode){ new Thread() { public void run() { try { Instrumentation inst = new Instrumentation(); inst.sendKeyDownUpSync(keyCode); } catch (Exception e) { e.printStackTrace(); } } }.start(); } 3.调用InputManager api(android 系统虚拟按键就是使用这种方法)

InputManager.getInstance().injectInputEvent 为隐藏方法,如果不是在系统中使用,则需要使用反射,或者将源码导入app,使其编译不报错。

long now = SystemClock.uptimeMillis(); KeyEvent down = new KeyEvent(now, now, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_1, 0); InputManager.getInstance().injectInputEvent(down, InputManager.INJECT_INPUT_EVENT_MODE_ASYNC); KeyEvent up = new KeyEvent(now, now, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_1, 0); InputManager.getInstance().injectInputEvent(up, InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3