Home » Android » Android click the back button to exit the applicat...

Android click the back button to exit the application

preface


needs to implement similar to the mainstream of the withdrawal function, continuous press two return key to exit the application.


program


first code:


import android.app.Activity;
Import android.os.Handler;
Import android.os.Looper;
Import android.view.KeyEvent;
Import android.widget.Toast;
/ * *
* double click to exit
*
* @author wxm
*
* /
Public, class, DoubleClickExitHelper {
Private final Activity mActivity;
Private Boolean isOnKeyBacking;
Private Handler mHandler;
Private Toast mBackToast;
Public DoubleClickExitHelper (Activity, activity) {
MActivity = activity;
MHandler = new, Handler (Looper.getMainLooper ());
}
/ * *
* Activity onKeyDown event
* * /
Public, Boolean, onKeyDown (int, keyCode, KeyEvent, event) {
If (keyCode = = KeyEvent.KEYCODE_BACK) {
Return false;
}
If (isOnKeyBacking) {
MHandler.removeCallbacks (onBackTimeRunnable);
If (mBackToast = = null) {
MBackToast.cancel ();
}
MActivity.finish ();
Return true;
} else {
IsOnKeyBacking = true;
If (mBackToast = = null) {
}
MHandler.postDelayed (onBackTimeRunnable, 2000);
Return true;
}
}
Private, Runnable, onBackTimeRunnable = new, Runnable () {
@Override
Public, void, run () {
IsOnKeyBacking = false;
If (mBackToast = = null) {
MBackToast.cancel ();
}
}
};
}
then calls the method:


private DoubleClickExitHelper doubleClickExitHelper;
@Override
Protected, void, onCreate (Bundle, savedInstanceState) {
DoubleClickExitHelper = new, DoubleClickExitHelper (this);
}
@Override
Public, Boolean, onKeyDown (int, keyCode, KeyEvent, event) {
If (keyCode = = KeyEvent.KEYCODE_BACK
& & event.getAction () = = KeyEvent.ACTION_DOWN) {
Toast.makeText (this, getString (R.string.back_exit_tips), Toast.LENGTH_SHORT),.Show ();
Return doubleClickExitHelper.onKeyDown (keyCode, event);
}
Return true;
}






Latest