package com.csdn.sunyudoong.csdn.ui;
import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.widget.Toast;
import com.csdn.sunyudoong.csdn.AppManager;
import com.csdn.sunyudoong.csdn.R;
/**
* 双击退出
* Created by sunyudong on 2016/6/6.
*/
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();
}
// 退出
AppManager.getAppManager().AppExit(mActivity);
return true;
} else {
//第一次点击
isOnKeyBacking = true;
if(mBackToast == null) {
mBackToast = Toast.makeText(mActivity, "再次点击退出开源中国", Toast.LENGTH_SHORT);
}
mBackToast.show();
//延迟两秒
mHandler.postDelayed(onBackTimeRunnable, 2000);
return true;
}
}
private Runnable onBackTimeRunnable = new Runnable() {
//两秒过后执行的事情
@Override
public void run() {
isOnKeyBacking = false;
if(mBackToast != null){
mBackToast.cancel();
}
}
};
}
调用方式,在需要调用的activity中的onKeyDown方法中调用
下面我是简写的,大家应该能够看懂,在一个activity中先定义对象
然后调用对象的方法
private DoubleClickExitHelper mDoubleClickExit;
mDoubleClickExit = new DoubleClickExitHelper(this);
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// 是否退出应用
return mDoubleClickExit.onKeyDown(keyCode, event);
}
return super.onKeyDown(keyCode, event);
}