前言

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();
    }
}

参考文章

  1. Android模拟产生事件 (race604.com)
  2. adb shell input 各参数的使用 -笔友城堡 – 阅读是一种生活方式 ()

相关文章

暂无评论

none
暂无评论...