Android 双击返回键退出应用程序

前言

需要实现类似于主流的退出功能,连续按两次返回键退出应用程序。

方案

先上代码:

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.widget.Toast;

/**
 * 双击退出
 * 
 * @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事件
	 * */
	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();
			}
		}
	};
}
然后调用方法:

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



你可能感兴趣的:(android,按两次退出程序)