新建一个类DoubleClickExitHelper.java
public class DoubleClickExitHelper { private final Activity mActivity; private boolean isOnKeyBacking; private Handler mHandler; private Toast mBackToast; public DoubleClickExitHelper(Activity activity) { mActivity = activity;//保存传进来的activity mHandler = new Handler(Looper.getMainLooper());//生成一个handler,去管理消息队列 } /** * 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;//注意,首先执行这里,因为isOnKeyBacking刚开始是false if (mBackToast == null) { mBackToast = Toast.makeText(mActivity, R.string.back_exit_tips, 2000); } mBackToast.show(); mHandler.postDelayed(onBackTimeRunnable, 2000);//加入消息队列, 2000ms之后执行 return true; } } // 2000ms之后执行, 把isOnKeyBacking设置成false private Runnable onBackTimeRunnable = new Runnable() { @Override public void run() { isOnKeyBacking = false; if (mBackToast != null) { mBackToast.cancel(); } } }; }
然后在主界面里面调用
Main.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // 双击返回键退出 mDoubleClickExitHelper = new DoubleClickExitHelper(this); } /** * 监听返回--是否退出程序 */ public boolean onKeyDown(int keyCode, KeyEvent event) { boolean flag = true; if (keyCode == KeyEvent.KEYCODE_BACK) { // 是否退出应用 return mDoubleClickExitHelper.onKeyDown(keyCode, event); } else if (keyCode == KeyEvent.KEYCODE_MENU) { // 其他 } else if (keyCode == KeyEvent.KEYCODE_SEARCH) { // 其他 } else { // 其他 } return flag; }
OK, 这样就可以实现了
时间: 2024-10-05 04:33:24