The function methods of implementing the back key are:
One: Rewrite the onbackpressed method
Copy Code code as follows:
@Override
public void onbackpressed () {
Do something what for you want
Super.onbackpressed ();
}
Second: Use test framework instrumentation, simulate any key press action, note that this method can not be used in the main thread, only open new threads, the problem is that the reaction is slow, the project is not recommended.
Call the Onback () method, and generate a back-click effect
public void Onback () {
new Thread () {public
void run () {
try{
Instrumentation inst = new Instrumentation ( );
Inst.sendkeydownupsync (Keyevent.keycode_back);
}
catch (Exception e) {
log.e ("Exception when Onback", e.tostring ());}}
. Start ();
}
Three: This method is collected on the network, no code verification.
try{
Runtime runtime=runtime.getruntime ();
Runtime.exec ("Input keyevent" + keyevent.keycode_back);
} catch (IOException e) {
log.e ("Exception when Doback", e.tostring ());
}
Four: Rewrite dispatchkeyevent
@Override Public
Boolean dispatchkeyevent (KeyEvent event) {
//TODO auto-generated method stub
if ( Event.getaction () = = Keyevent.action_down
&& event.getkeycode () = = Keyevent.keycode_back) {
//do Something what your want
return true;//returns True, consumes the event, does not continue to invoke onbackpressed
}
Super.dispatchkeyevent (event);
}
Five: This method is not the full meaning of the back key function, this method can only close the current activity, that is, for a single activity of the application is effective, if there are many external activity of the application it is powerless.
Copy Code code as follows:
public void Exitprogrames () {
Android.os.Process.killProcess (Android.os.Process.myPid ());
}
Additional permissions are required to use this method: <uses-permission android:name= "Android.permission.RESTART_PACKAGES"/>