Android的简单应用(二)——使用dispatchKeyEvent双击退出程序
Android系统按键操作最先是在dispatchKeyEvent中进行处理的,然后才是onKeyDown(int keyCode, KeyEvent event)和onKeyUp(int keyCode, KeyEvent event)。
同理,触摸操作也是先在dispatchTouchEvent中进行处理,在分发给onTouchEvent进行处理。
代码很简单,只要掌握好事件的分发顺序就ok了。
Activity中的代码:
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub Log.d("CPACM","onKeyDown"); return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { // TODO Auto-generated method stub Log.d("CPACM","onKeyUp"); return super.onKeyUp(keyCode, event); } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub Log.d("CPACM","onTouchEvent"); return super.onTouchEvent(event); } @Override public boolean dispatchKeyEvent(KeyEvent event) { Log.d("CPACM","dispatchKeyEvent"); if(event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){ if(System.currentTimeMillis() - preTime < 2000){//在两秒内,退出 return super.dispatchKeyEvent(event); }
Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
//System.exit(0); preTime = System.currentTimeMillis(); return true; } // TODO Auto-generated method stub return super.dispatchKeyEvent(event); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { // TODO Auto-generated method stub Log.d("CPACM","dispatchTouchEvent"); return super.dispatchTouchEvent(ev); }
顺便附一张截图~
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。