用法:
Usage: input [<source>] <command> [<arg>...]
其中,source有:
mouse, keyboard,joystick,touchnavigation
touchpad,trackball,stylus,dpad,touchscreen,gamepad
默认的souces和commands:
text <string> (Default: touchscreen) keyevent [--longpress] <key code number or name> ... (Default: keyboard) tap <x> <y> (Default: touchscreen) swipe <x1> <y1> <x2> <y2> [duration(ms)] (Default: touchscreen) press (Default: trackball) roll <dx> <dy> (Default: trackball)
用法举例:发用一个MENU按键事件input keyevent 82 //发送menu按键,可以让app弹出menu菜单,menu的键值是82
如果不知道keycode,也可以直接用名字:input keyevent MENU //这样也可以让app弹出menu菜单
2.使用Instrumentation发送模拟按键
public static void simulateKey(final int KeyCode) { new Thread() { @Override public void run() { try { Instrumentation inst = new Instrumentation(); inst.sendKeyDownUpSync(KeyCode); } catch (Exception e) { Log.e("hello", e.toString()); } } }.start(); }
上面这段代码是我google到的,他确实很管用。 Instrumentation可以用户检测应用程序与系统的交互,经常用于软件测试当中,这个类功能强大,感兴趣的可以深入挖掘一下,这里只引出它发送按键事件的功能。在代码中调用simulateKey(82);则可以发送一个Menu事件,效果和input keyevent 82是一样的。
public static void simulateKeyByCommand(final int KeyCode){ try{ String keyCommand = "input keyevent " +KeyCode; Runtime runtime = Runtime.getRuntime(); Process proc = runtime.exec(keyCommand); } catch(IOException e){ //Log.e(TAG, e.toString()); } }