Simulating Touch Screen Events on Android

不羁岁月 提交于 2019-12-04 09:49:37

There is a tool that comes with the SDK called Monkey which generates pseudo-random streams of user events such as:

  • clicks
  • touches
  • gestures
  • a number of system-level events.

You can use the Monkey to stress-test applications that you are developing, in a random yet repeatable manner.

There is also the monkeyrunner tool which provides an API for writing programs that control an Android device or emulator from outside of Android code. With monkeyrunner, you can write a Python program that installs an Android application or test package, runs it, sends keystrokes to it, takes screenshots of its user interface, and stores screenshots on the workstation.

For button presses, you can use the following:

dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,
                KeyEvent.KEYCODE_BACK));

dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP,
                KeyEvent.KEYCODE_BACK));

A list of available keycodes can be found here: http://developer.android.com/reference/android/view/KeyEvent.html

For touchscreen events, you can use:

 dispatchTouchEvent(MotionEvent.obtain(
                    SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
                    MotionEvent.ACTION_DOWN, Xinput, Yinput, 0));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!