最近参加某比赛写了一个Android手机控制Android电视的程序,其中需要控制电视端模拟“鼠标”点击,和模拟按键盘的事件。
下面直接贴上程序:
/*** 触发屏幕点击事件* @param x 点击位置的x值* @param y 点击位置的y值*/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();}/*** 触发按键事件* @param keycode android键盘按键的keycode*/public void setKeyPress(int keycode){try { String keyCommand = "input keyevent " + keycode; Runtime runtime = Runtime.getRuntime(); Process proc = runtime.exec(keyCommand); } catch (IOException e) { e.printStackTrace(); }}
<!-- 模拟按键 --><uses-permission android:name = "android.permission.INJECT_EVENTS"/>
如果觉得《【Android】代码实现模拟屏幕点击和键盘按键事件》对你有帮助,请点赞、收藏,并留下你的观点哦!