安卓Monkey测试屏蔽特殊按键
程序员文章站
2022-07-14 20:58:15
...
有时候我们需要屏蔽掉Monkey脚本的部分按键,先看看Monkey的key事件生成代码:
外部获取MonkeyEvent是通过development/cmds/monkey/src/com/android/commands/monkey/MonkeySourceRandom.java
/**
* if the queue is empty, we generate events first
* @return the first event in the queue
*/
public MonkeyEvent getNextEvent() {
if (mQ.isEmpty()) {
generateEvents();
}
mEventCount++;
MonkeyEvent e = mQ.getFirst();
mQ.removeFirst();
return e;
}
这里先判断队列MQ是否为空,如果为空,生成一个事件。获取队列头部的事件,然后返回。
* generate a random event based on mFactor
*/
private void generateEvents() {
float cls = mRandom.nextFloat();
int lastKey = 0;
if (cls < mFactors[FACTOR_TOUCH]) {
generatePointerEvent(mRandom, GESTURE_TAP);
return;
} else if (cls < mFactors[FACTOR_MOTION]) {
generatePointerEvent(mRandom, GESTURE_DRAG);
return;
} else if (cls < mFactors[FACTOR_PINCHZOOM]) {
generatePointerEvent(mRandom, GESTURE_PINCH_OR_ZOOM);
return;
} else if (cls < mFactors[FACTOR_TRACKBALL]) {
generateTrackballEvent(mRandom);
return;
} else if (cls < mFactors[FACTOR_ROTATION]) {
generateRotationEvent(mRandom);
return;
} else if (cls < mFactors[FACTOR_PERMISSION]) {
mQ.add(mPermissionUtil.generateRandomPermissionEvent(mRandom));
return;
}
// The remaining event categories are injected as key events
for (;;) {
if (cls < mFactors[FACTOR_NAV]) {
lastKey = NAV_KEYS[mRandom.nextInt(NAV_KEYS.length)];
} else if (cls < mFactors[FACTOR_MAJORNAV]) {
lastKey = MAJOR_NAV_KEYS[mRandom.nextInt(MAJOR_NAV_KEYS.length)];
} else if (cls < mFactors[FACTOR_SYSOPS]) {
lastKey = SYS_KEYS[mRandom.nextInt(SYS_KEYS.length)];
} else if (cls < mFactors[FACTOR_APPSWITCH]) {
MonkeyActivityEvent e = new MonkeyActivityEvent(mMainApps.get(
mRandom.nextInt(mMainApps.size())));
mQ.addLast(e);
return;
} else if (cls < mFactors[FACTOR_FLIP]) {
MonkeyFlipEvent e = new MonkeyFlipEvent(mKeyboardOpen);
mKeyboardOpen = !mKeyboardOpen;
mQ.addLast(e);
return;
} else {
lastKey = 1 + mRandom.nextInt(KeyEvent.getMaxKeyCode() - 1);
}
if (lastKey != KeyEvent.KEYCODE_POWER
&& lastKey != KeyEvent.KEYCODE_ENDCALL
&& lastKey != KeyEvent.KEYCODE_SLEEP
&& lastKey != KeyEvent.KEYCODE_SOFT_SLEEP
&& PHYSICAL_KEY_EXISTS[lastKey]) {
break;
}
}
MonkeyKeyEvent e = new MonkeyKeyEvent(KeyEvent.ACTION_DOWN, lastKey);
mQ.addLast(e);
e = new MonkeyKeyEvent(KeyEvent.ACTION_UP, lastKey);
mQ.addLast(e);
}
这个generateEvents()是用来生成随机事件的,通过float类型的随机数cls,根据区间去生成触摸/拖动/缩放等动作事件。如果cls>=mFactors[FACTOR_PERMISSION]),则生成key事件。key事件也分好几个种类,如果生成的lastKey满足下面条件或者cls满足某些可以return的分支则中止,否则继续循环,直到生成合适的key事件。
if (lastKey != KeyEvent.KEYCODE_POWER
&& lastKey != KeyEvent.KEYCODE_ENDCALL
&& lastKey != KeyEvent.KEYCODE_SLEEP
&& lastKey != KeyEvent.KEYCODE_SOFT_SLEEP
&& PHYSICAL_KEY_EXISTS[lastKey]) {
break;
}
如果我们要屏蔽某些特殊按键,就直接在上面的if()条件中加入lastKey!= xxx就可以屏蔽掉想要屏蔽的按键了。
上一篇: Struts2 验证框架
下一篇: Lake Counting