1. 程式人生 > >Android 雙擊返回鍵退出APP

Android 雙擊返回鍵退出APP

    private boolean isExit=false;//是否退出APP

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK) {
            appExit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void appExit() {
        if(!isExit) {
            isExit=true;
            showToast(this,"再按一次退出程式");
            exitHandler.sendEmptyMessageDelayed(0,2000);
        } else {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            System.exit(0);
        }
    }
    private Handler exitHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit=false;
        }
    };