When you select "cancel", you only need to retuan to return to the main program.
We can define a dedicated showTips () method in the main Activity, so every time we write, we can call this function.
Copy codeThe Code is as follows: private void showTips (){
AlertDialog alertDialog = new AlertDialog. Builder (Activity. this)
. SetTitle ("Exit program ")
. SetMessage ("Exit program ")
. SetPositiveButton ("OK", new DialogInterface. OnClickListener (){
Public void onClick (DialogInterface dialog, int which)
Activity. this. finish ();
}
})
. SetNegativeButton ("cancel ",
New DialogInterface. OnClickListener (){
Public void onClick (DialogInterface dialog, int which)
Return;
}). Create (); // create dialog box
AlertDialog. show (); // displayed dialog box
}
So where can I call this prompt?
At first, my idea was to define it in the onDestory () function of the main Activity of Android. Then I tried it and found that the function was actually exited when the Activity exited, it will be called. If it is called here, it will be too late.
Therefore, we should find the response time of the return button, that is, the response event in the function Activity. onKeyDown (int keyCode, KeyEvent event.
Copy codeThe Code is as follows: @ Override
Public boolean onKeyDown (int keyCode, KeyEvent event ){
If (keyCode = KeyEvent. KEYCODE_BACK & event. getRepeatCount () = 0 ){
This. showTips ();
Return false;
}
Return false;
}
Now, the onKeyDown function is rewritten. When you click the return button, a prompt dialog box is displayed to effectively prevent unnecessary exit caused by errors.
Implement android to exit the program code again
Copy codeThe Code is as follows: private long exitTime = 0;
/**
* Capture the return event button
*
* Because this Activity inherits TabActivity and does not respond with onKeyDown, use dispatchKeyEvent instead.
* Generally, you can use onKeyDown for an Activity.
*/
@ Override
Public boolean dispatchKeyEvent (KeyEvent event ){
If (event. getKeyCode () = KeyEvent. KEYCODE_BACK ){
If (event. getAction () = KeyEvent. ACTION_DOWN & event. getRepeatCount () = 0 ){
This. exitApp ();
}
Return true;
}
Return super. dispatchKeyEvent (event );
}
/**
* Exit the program.
*/
Private void exitApp (){
// Determine the time of two click events
If (System. currentTimeMillis ()-exitTime)> 2000 ){
Toast. makeText (MainActivity. this, "exit the program again", Toast. LENGTH_SHORT). show ();
ExitTime = System. currentTimeMillis ();
} Else {
Finish ();
}
}