组合键用队列的方式
按键事件在dispatchKeyEvent中
public class MainActivity extends AppCompatActivity {
private long extTime = 0L;
private Queue<Integer> targetQ = new LinkedList<>();
private Queue<Integer> currentQ = new LinkedList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
targetQ.add(KeyEvent.KEYCODE_DPAD_UP);
targetQ.add(KeyEvent.KEYCODE_DPAD_UP);
targetQ.add(KeyEvent.KEYCODE_DPAD_DOWN);
targetQ.add(KeyEvent.KEYCODE_DPAD_DOWN);
targetQ.add(KeyEvent.KEYCODE_DPAD_LEFT);
targetQ.add(KeyEvent.KEYCODE_DPAD_LEFT);
targetQ.add(KeyEvent.KEYCODE_DPAD_RIGHT);
targetQ.add(KeyEvent.KEYCODE_DPAD_RIGHT);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN){
switch ((event.getKeyCode())){
case KeyEvent.KEYCODE_BACK:
if (System.currentTimeMillis() -extTime >2000){
Toast.makeText(this, "再按一次返回键退出", Toast.LENGTH_SHORT).show();
extTime = System.currentTimeMillis();
}else {
finish();
System.exit(0);
}
return true;
}
keyDownRecord(event.getKeyCode());
}
return super.dispatchKeyEvent(event);
}
/**
* 在本页面连续并顺序的按了"上上下下左左右右"
*
* @param keyCode
*/
private void keyDownRecord(int keyCode) {
currentQ.offer(keyCode);
if (currentQ.size() > targetQ.size()) {
currentQ.poll();//删除并返回Queue中的头元素。如果queue为空,返回NULL
}
if (currentQ.equals(targetQ))
Toast.makeText(this, "在本页面连续并顺序的按了:上上下下左左右右", Toast.LENGTH_SHORT).show();
}
}