Simple Application of Android (2) -- double-click dispatchKeyEvent to exit the program and dispatchkeyevent
In the Android system, key operations are processed in dispatchKeyEvent first, and then onKeyDown (int keyCode, KeyEvent event) and onKeyUp (int keyCode, KeyEvent event ).
Similarly, the touch operation is first processed in the dispatchTouchEvent and then processed in the distribution to the onTouchEvent.
The code is very simple, as long as you have a good grasp of the event distribution order is OK.
Code in 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) {// within two seconds, exit return super. dispatchKeyEvent (event );}
Toast. makeText (this, "exit the program again", 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 );}
By the way, a copy is provided ~