Android Home Key Monitor
Android Normal key value can be processed directly in dispatchkeyevent (), but the home key, more special, need to monitor its broadcast separately, and must be dynamic broadcast, its static broadcast is invalid;
Requirements: Home key, set Kill yourself, but there are multiple activity in the Activiy, in each middle-aged listening home key broadcast is not realistic, must be the interception of radio to be implemented in the same class, taking into account the baseactivity;
Public classBaseactivityextendsActivity {PrivateHomewatcherreceiver Mhomewatcherreceiver =NULL; Private BooleanIsneedfinish =false; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Registerreceiver (); } Public voidSetbackfinish (Booleanflag) {Isneedfinish=Flag; } Private voidRegisterreceiver () {Mhomewatcherreceiver=NewHomewatcherreceiver (); Intentfilter Filter=NewIntentfilter (intent.action_close_system_dialogs); Registerreceiver (mhomewatcherreceiver, filter); } @Override Public Booleandispatchkeyevent (KeyEvent event) {intKeyCode =Event.getkeycode (); if(event.getaction () = =Keyevent.action_down) { if(Event.getkeycode () = =keyevent.keycode_back) { This. Finish (); System.GC (); return true; } } return Super. Dispatchkeyevent (event); } Public classHomewatcherreceiverextendsBroadcastreceiver {Private Static FinalString System_dialog_reason_key = "REASON"; Private Static FinalString System_dialog_reason_home_key = "HomeKey"; @Override Public voidOnReceive (Context context, Intent Intent) {String intentaction=intent.getaction (); LOG.I (MyAPP,"Intentaction =" +intentaction); if(Textutils.equals (intentaction, intent.action_close_system_dialogs)) {String reason=Intent.getstringextra (System_dialog_reason_key); LOG.I (MyAPP,"Reason =" +reason); if(Textutils.equals (System_dialog_reason_home_key, REASON)) {baseactivity. This. Finish (); } }} @Overrideprotected voidOnDestroy () {Super. OnDestroy (); if(Mhomewatcherreceiver! =NULL) { Try{unregisterreceiver (mhomewatcherreceiver); } Catch(Exception e) {e.printstacktrace (); } } }}
"Android Advanced" Android Home key monitor