前言
Instrumentation本身是Android用来做测试的工具,可以通过它监测系统与应用程序之间的交互。
本文就介绍Instrumentation在应用中的简单使用。
正文
模拟事件需要权限
<uses-permission android:name="android.permission.INJECT_EVENTS"/>
我测试时用的系统应用,所以
模拟按键
public static void sendSystemKey(final int keyCode) {
try {
new Thread(new Runnable() {
@Override
public void run() {
(new Instrumentation()).sendKeyDownUpSync(keyCode);
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
}
模拟触摸事件
public static void sendTouchXY(final int x, final int y) {
try {
new Thread(new Runnable() {
@Override
public void run() {
Instrumentation instrumentation = new Instrumentation();
instrumentation.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),
SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, x, y, 0));
instrumentation.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),
SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, x, y, 0));
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
}
参考文章
© 版权声明