一、应用中模拟物理和屏幕点击事件
例如,模拟对某个view的点击事件
private void simulateClick(View view, float x, float y) {
long downTime = SystemClock.uptimeMillis();
final MotionEvent downEvent = MotionEvent.obtain(downTime, downTime,MotionEvent.ACTION_DOWN, x, y, 0);
downTime += 1000;
final MotionEvent upEvent = MotionEvent.obtain(downTime, downTime,MotionEvent.ACTION_UP, x, y, 0);
view.onTouchEvent(downEvent);
view.onTouchEvent(upEvent);
downEvent.recycle();
upEvent.recycle();
}
public void setMouseClick(int x, int y){
MotionEvent evenDownt = MotionEvent.obtain(System.currentTimeMillis(),
System.currentTimeMillis() + 100, MotionEvent.ACTION_DOWN, x, y, 0);
dispatchTouchEvent(evenDownt);
MotionEvent eventUp = MotionEvent.obtain(System.currentTimeMillis(),
System.currentTimeMillis() + 100, MotionEvent.ACTION_UP, x, y, 0);
dispatchTouchEvent(eventUp);
evenDownt.recycle();
eventUp.recycle();
}
这实现原理就是模拟两个MotionEvent (按下和提起) 然后用一个View 来处理这个Event 。
二、Instrumentation实现模拟键盘鼠标事件
// 可以不用在 Activity 中增加任何处理,各 Activity 都可以响应
Instrumentation inst = new Instrumentation();
inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),
MotionEvent.ACTION_DOWN, 200, 500, 0));
inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),
MotionEvent.ACTION_UP, 200, 500, 0));