There are two common ways to exit an Android project: The Pop-Up dialog dialog prompts the user to exit the application, and the following two implementation forms have an indication of the code to refer to.
First pop-up dialog style exit mode:
1. The first step is to monitor whether the user presses the back key, to rewrite the onkeydown ()
2. Build dialog
The main code is as follows:
@Override
public boolean onKeyDown (int keycode, keyevent event) {
if (event! = NULL && KeyCode = = event. Keycode_back) {
Alertdialog ();
}
return false;
}
private void Alertdialog () {
Charsequence chartitle = "Exit";
Charsequence Charmessage = "Are you sure you want to quit?";
charsequence [] charsequence = new charsequence[]{"OK", "Cancel"};
Alertdialog.builder Alertdialog = new Alertdialog.builder (mactivity)
. SetIcon (R.drawable.ic_launcher)//Set head picture
. Settitle (Chartitle)//Set title
. Setmessage (Charmessage)//Set prompt content
. Setpositivebutton (Charsequence[0], new Dialoginterface.onclicklistener () {//OK button listener
@Override
public void OnClick (Dialoginterface dialog, int which) {
/**
* Can add Project processing logic
*/
Mactivity.finish ();
}
})
. Setnegativebutton (Charsequence[1], new Dialoginterface.onclicklistener () {//Cancel button listener
@Override
public void OnClick (Dialoginterface dialog, int which) {
}
});
Alertdialog.show ();
}
The effect is as follows:
Second double-click two times back key exit style
The main code is as follows:
@Override
public boolean onKeyDown (int keycode, keyevent event) {
if (event! = NULL && KeyCode = = event. Keycode_back) {
Exitapp ();
}
return false;
}
/**
* Double Knockback out app
*/
Private Boolean isexit = false;
private void Exitapp () {
if (Isexit = = False) {
Isexit = true;
Toast.maketext (mactivity, "Click again to exit", Toast.length_long). Show ();
Timer timer = new timer ();
Timer.schedule (New TimerTask () {
@Override
public void Run () {
Isexit = false;
}
}, 2000);
}else{
Mactivity.finish ();
}
}
As follows:
Another way to achieve this:
@Override
public void onbackpressed () {
if (Backtofinish ()) finish ();
}
/**
* Double click to exit
*/
private int back = 0;
Private Boolean backtofinish () {
if (back==0) {
back++;
Toast.maketext (Mactivity, "Press again to exit", Toast.length_short). Show ();
New Thread (New Runnable () {
@Override
public void Run () {
try {
Thread.Sleep (1500);
back--;
} catch (Exception e) {
E.printstacktrace ();
}
}
}). Start ();
return false;
}else if (back==1) {
return true;
}
return true;
}
The content is very simple, hope to be helpful to you!
Android APP Exit method