Android 返回键连续点击两次退出应用

返回键连续点击两次退出应用,一般大家都是使用时间差来实现功能,现在推荐使用handler来实现,看代码

使用工具类[b]DoubleClickExitHelper[/b]

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();
}
}
};
}


[b]接下来我们只需要在回调onKeyDown中加入该工具方法即可,当然使用前要初始化下[/b]
DoubleClickExitHelper doubleClick = new DoubleClickExitHelper(this);

[b]接下来重写onKeyDown:[/b]
/**
* Returns:
* Return
* true to prevent this event from being propagated further, or false to
* indicate that you have not handled this event and it should continue to
* be propagated.
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
return doubleClick.onKeyDown(keyCode, event);
}
return super.onKeyDown(keyCode, event);
}

[b]完成,方便简单[/b]

你可能感兴趣的:(android,android,双击返回键)