工具类DoubleClickExitHelper
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事件
* */
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) {
mBackToast = Toast.makeText(mActivity, "再按一次返回", 2000);
}
mBackToast.show();
//延迟两秒的时间,把Runable发出去
mHandler.postDelayed(onBackTimeRunnable, 2000);
return true;
}
}
private Runnable onBackTimeRunnable = new Runnable() {
@Override
public void run() {
isOnKeyBacking = false;
if(mBackToast != null){
mBackToast.cancel();
}
}
};
}
接下来我们只需要在回调onKeyDown中加入该工具方法即可,当然要初始化一下
DoubleClickExitHelper doubleClick = new DoubleClickExitHelper(this);
最后重写重写onKeyDown:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
return doubleClick.onKeyDown(keyCode, event);
}
return super.onKeyDown(keyCode, event);
}
转载至:http://javaeedyc.iteye.com/blog/2165098
最近又发现一个更简单的方法
private long mPreTime = 0;
@Override
public void onBackPressed() {
if (System.currentTimeMillis() - mPreTime > 2000) {
Toast.makeText(this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
mPreTime = System.currentTimeMillis();
return;
} else {
finish();
super.onBackPressed();
}
}