美文网首页
Android输入事件模拟

Android输入事件模拟

作者: ravenal | 来源:发表于2018-02-27 17:01 被阅读0次

在一些自动化测试等情景下,输入Android应用程序产生一些屏幕点击等的输入事件以实现特定需求。本文总结了几种Android中模拟产生输入事件的方式。

1 Shell命令

在Android中有两个shell中运行的工具可以模拟产生输入事件inputsendevent。由于sendevent需要用到相应的设备,需要考虑权限问题,因此一般不常用,这里只介绍input。

Usage: input [<source>] <command> [<arg>...]

The sources are:  
      trackball
      joystick
      touchnavigation
      mouse
      keyboard
      gamepad
      touchpad
      dpad
      stylus
      touchscreen

The commands and default sources are:  
      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)
      tmode <tmode>

如点击屏幕(200,300)处只需要如下命令即可:

$ input tap 200 300

2 Instrumentation

Instrumentation是Android提供的一个测试工具,可以通过它监测系统与应用程序之间的交互。使用此方法需要如下的system权限:

<uses-permission android:name="android.permission.INJECT_EVENTS"/>  

Instrumentation模拟点击屏幕(200,300)事件的方法如下:

Instrumentation instrument= new Instrumentation();  
instrument.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),  SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 200, 300, 0);
instrument.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 200, 300, 0);

3 InputManager

Android Inputmanager的injectEvent()方法也可以模拟产生输入事件(API16以上版本)。不过此方法属于隐藏方法,需要反射调用,这里不作具体描述。


1 https://www.pocketmagic.net/injecting-events-programatically-on-android/#.VKn42M2UfCI

相关文章

网友评论

      本文标题:Android输入事件模拟

      本文链接:https://www.haomeiwen.com/subject/jqdmxftx.html