直播平台软件开发,Android代码模拟触摸、点击及滑动等事件
一、应用中模拟物理和屏幕点击事件
例如,模拟对某个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));
以上就是 直播平台软件开发,Android代码模拟触摸、点击及滑动等事件,更多内容欢迎关注之后的文章
标签:MotionEvent,软件开发,触摸,uptimeMillis,obtain,downTime,ACTION,Android,模拟 From: https://www.cnblogs.com/yunbaomengnan/p/17309616.html