The methods to implement Back key functions are:
One: Rewrite the onBackPressed method
@Override
public void onBackPressed() {
// do something what you want
();
}
2: Use the test framework Instrumentation to simulate the action of pressing any key. Note that this method cannot be used in the main thread and can only open a new thread. The problem is that the reaction speed is slow and it is not recommended to use it in the project.
Call the onBack() method; generate a back key click effect
public void onBack(){ new Thread(){ public void run() { try{ Instrumentation inst = new Instrumentation(); (KeyEvent.KEYCODE_BACK); } catch (Exception e) { ("Exception when onBack", ()); } } }.start(); }
3: This method is collected on the Internet and has no code verification.
try{ Runtime runtime=(); ("input keyevent " + KeyEvent.KEYCODE_BACK); }catch(IOException e){ ("Exception when doBack", ()); }
Four: Rewrite dispatchKeyEvent
@Override public boolean dispatchKeyEvent(KeyEvent event) { // TODO Auto-generated method stub if (() == KeyEvent.ACTION_DOWN && () == KeyEvent.KEYCODE_BACK) { //do something what you want return true;//Return true, consume the event, and will not continue to call onBackPressed } return (event); }
5: This method is not a complete function of the Back key. This method can only turn off the current Activity, which means it is effective for an application with only a single Activity. If it is powerless for an application with more than one Activity, it will be powerless.
public void exitProgrames(){
(());
}
Use this method to append permissions: <uses-permission android:name=".RESTART_PACKAGES" />