When the user chooses "Cancel", as long as the simple Retuan, can return the main program.
We can define a showtips () specific method in the main activity, so every time we write, we call this function.
Copy Code code as follows:
private void Showtips () {
Alertdialog Alertdialog = new Alertdialog.builder (activity.this)
. Settitle ("Exit program")
. Setmessage ("Quit 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 a dialog box
Alertdialog.show (); Show dialog box
}
So, where is the method of calling this hint?
Originally my idea was to be defined in the Ondestory () function inside the Android main activity, and later tried to find out that the function was actually invoked when the activity exited, and it was too late if it was called here.
So, what should be found is the response time to return the key, which is the function activity. The OnKeyDown (int keycode, keyevent event) function responds to the occurrence of the event.
Copy Code code as follows:
@Override
public boolean onKeyDown (int keycode, keyevent event) {
if (Keycode==keyevent.keycode_back && event.getrepeatcount () ==0) {
This.showtips ();
return false;
}
return false;
}
At this point, through the replication onkeydown function, when the user clicks the returned button, Pop-up prompts dialog box, can effectively prevent users due to errors caused by unnecessary exit.
Implement Android and press exit program code again
Copy Code code as follows:
Private long exittime = 0;
/**
* Capture Return Event button
*
* For this activity to inherit tabactivity with OnKeyDown no response, so switch to Dispatchkeyevent
* General activity with OnKeyDown on it
*/
@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 procedure
*/
private void Exitapp () {
Determine the time of 2 click events
if ((System.currenttimemillis ()-Exittime) > 2000) {
Toast.maketext (Mainactivity.this, "Press the exit procedure again", Toast.length_short). Show ();
Exittime = System.currenttimemillis ();
} else {
Finish ();
}
}