When the user selects "Cancel", just simply retuan and return to the main program.
We can define a special method of showTips() in the main activity, so every time we write, we just call this function.
private void showTips(){
AlertDialog alertDialog = new ()
.setTitle("Exit Program")
.setMessage("Does it exit the program")
.setPositiveButton("OK", new () {
public void onClick(DialogInterface dialog, int which)
();
}
})
.setNegativeButton("Cancel",
new () {
public void onClick(DialogInterface dialog, int which)
return;
}}).create(); //Create dialog box
(); // Show dialog box
}
So, where to call this prompt method?
At first, my idea was to define it in the onDestory() function in the main activity of Android. Later, I tried it and found that this function was actually called when the Activity exited. If it was called here, it would be too late.
Therefore, what should be found is the response time of the return key, that is, the function Activity. onKeyDown(int keyCode, KeyEvent event) The occurrence of the response event in the function.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK && ()==0){
();
return false;
}
return false;
}
At this point, by rewriting the onKeyDown function, a prompt dialog box will pop up when the user clicks the returned button, which can effectively prevent the user from exiting due to errors.
Implement android and press the exit program code again
private long exitTime = 0;
/**
* Catch Return Event Button
*
* Because this Activity inherits TabActivity and uses onKeyDown to not respond, use dispatchKeyEvent instead
* For general activities, just use onKeyDown
*/
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (() == KeyEvent.KEYCODE_BACK) {
if (() == KeyEvent.ACTION_DOWN && () == 0) {
();
}
return true;
}
return (event);
}
/**
* Exit the program
*/
private void exitApp() {
//Judge the time of 2 click events
if ((() - exitTime) > 2000) {
(, "Press again to exit the program", Toast.LENGTH_SHORT).show();
exitTime = ();
} else {
finish();
}
}