(1)模拟按键发送事件
1.1 在dispatchKeyvent中直接替换按键Code
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
//有些定制机没有左右键,用上下键和音量加减键模拟左右键,控制音量大小。
if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_UP) {
event.setKeyCode(KeyEvent.KEYCODE_DPAD_RIGHT);
} else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN) {
event.setKeyCode(KeyEvent.KEYCODE_DPAD_LEFT);
}else if(event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP){//音量上键
event.setKeyCode(KeyEvent.KEYCODE_DPAD_RIGHT);//右键
}else if(event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN){
event.setKeyCode(KeyEvent.KEYCODE_DPAD_LEFT);
}
return super.dispatchKeyEvent(event);
}
1.2 监听某个按键,替换按键code
mTitle.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
//返回键专门用来返回,删除功能由A3完成.
if(KeyEvent.KEYCODE_BACK == keyEvent.getKeyCode()){
onBackPressed();
return true;
}
//A3专门作为删除字符串作用.
if(KeyEvent.KEYCODE_A3 == keyEvent.getKeyCode() && KeyEvent.ACTION_DOWN == keyEvent.getAction()){
keyEvent.setKeyCode(KeyEvent.KEYCODE_DEL);//删除字符串
mTitle.dispatchKeyEvent(keyEvent);
return true;
}
return false;
}
});
简单的代码,记录一下。
(2)模拟触摸点击,和模拟滑动,有些场景可能会用到。
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
WindowManager win=getWindowManager();
Display display=win.getDefaultDisplay();
int width=display.getWidth();
int height=display.getHeight();
if(keyCode==KeyEvent.KEYCODE_DPAD_CENTER){
//点击屏幕中点
setMouseClick(width/2,height/2);
}else if(keyCode==KeyEvent.KEYCODE_DPAD_RIGHT){
//向右滑动屏幕
onFling(width/2,height/2,"right");
}else if(keyCode==KeyEvent.KEYCODE_DPAD_LEFT){
//向左滑动屏幕
onFling(width/2,height/2,"left");
}
return super.onKeyUp(keyCode, event);
}
//模拟触摸点击
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();
}
//模拟滑动
public void onFling(final int x, final int y,final String leftRight){
new Thread(new Runnable() {
@Override
public void run() {
Instrumentation inst = new Instrumentation();
long dowTime = SystemClock.uptimeMillis();
int distance=0;
if(leftRight.equals("right")){//right,next
distance=x-20;
}else{//left,previous
distance=x+20;
}
inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime,
MotionEvent.ACTION_DOWN, x, y,0));
inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime,
MotionEvent.ACTION_MOVE, x, y,0));
inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime+20,
MotionEvent.ACTION_MOVE, distance, y,0));
inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime+20,
MotionEvent.ACTION_UP, distance, y,0));
inst.setInTouchMode(false);//如果是键盘机,不能是触摸模式,否则无焦点
}
}).start();
}
参考来源:
https://www.cnblogs.com/zhujiabin/p/6971475.html
https://blog.csdn.net/linghaidong/article/details/53408002