首页 > 学院 > 开发设计 > 正文

再按一次退出——两种方式实现

2019-11-09 17:34:55
字体:
来源:转载
供稿:网友

    方式一:

PRivate boolean isExit = false;private Handler mHandler = new Handler() {    @Override    public void handleMessage(Message msg) {        switch (msg.what) {            case 0:                isExit = false;                break;        }    }};@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {    if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {        if (isExit) {            mHandler.removeCallbacksAndMessages(null);        } else {            isExit = true;            mHandler.sendEmptyMessageDelayed(0, 3000);            Toast.makeText(MainActivity.this, "再按一次退出", Toast.LENGTH_SHORT).show();            return true;        }    }    return super.onKeyDown(keyCode, event);}

方式二:

   

private long exitTime = 0;@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {    if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {        if (System.currentTimeMillis() - exitTime > 3000) {            Toast.makeText(getapplicationContext(), "再按一次返回键退出", Toast.LENGTH_SHORT).show();            exitTime = System.currentTimeMillis();        } else {            finish();        }        return true;    }    return super.onKeyDown(keyCode, event);}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表