最近参加某比赛写了一个Android手机控制Android电视的程序,其中需要控制电视端模拟“鼠标”点击,和模拟按键盘的事件。
下面直接贴上程序:
// 模拟屏幕点击事件
public void setMouseClick(){
MotionEvent evenDownt = MotionEvent.obtain(System.currentTimeMillis(), System.currentTimeMillis() + 100, MotionEvent.ACTION_DOWN, imgMouse.getX(), imgMouse.getY(), 0);
dispatchTouchEvent(evenDownt);
MotionEvent eventUp = MotionEvent.obtain(System.currentTimeMillis(), System.currentTimeMillis() + 100, MotionEvent.ACTION_UP, imgMouse.getX(), imgMouse.getY(), 0);
dispatchTouchEvent(eventUp);
evenDownt.recycle();
eventUp.recycle();
}
// 模拟键盘按键,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();
}
}
转载于:https://blog.51cto.com/dvlee/1351056