The key operation of the Android system is first processed in Dispatchkeyevent, then onkeydown (int keycode, keyevent event) and onkeyup (int keycode, keyevent Event).
In the same vein, touch operations are processed first in dispatchtouchevent and distributed to ontouchevent.
The code is simple, so long as you have a good command of the event's distribution order is OK.
Code in activity:
@Override Public BooleanOnKeyDown (intKeyCode, KeyEvent event) { //TODO auto-generated Method StubLOG.D ("CPACM", "OnKeyDown"); return Super. OnKeyDown (KeyCode, event); } @Override Public BooleanOnKeyUp (intKeyCode, KeyEvent event) { //TODO auto-generated Method StubLOG.D ("CPACM", "OnKeyUp"); return Super. OnKeyUp (KeyCode, event); } @Override Public Booleanontouchevent (Motionevent event) {//TODO auto-generated Method StubLOG.D ("CPACM", "Ontouchevent"); return Super. Ontouchevent (event); } @Override Public Booleandispatchkeyevent (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, "Press again to exit the program", Toast.length_short). Show ();
//system.exit (0); Pretime=System.currenttimemillis (); return true; } //TODO auto-generated Method Stub return Super. Dispatchkeyevent (event); } @Override Public Booleandispatchtouchevent (motionevent ev) {//TODO auto-generated Method StubLOG.D ("CPACM", "Dispatchtouchevent"); return Super. dispatchtouchevent (EV); }
By the way, a piece ~
Android simple App (ii)--use dispatchkeyevent double exit program