美文网首页
2020-07-29Android连点2次back键退出

2020-07-29Android连点2次back键退出

作者: lodtap | 来源:发表于2020-07-29 16:54 被阅读0次

    方法1

    private boolean isQuit =false;

    @Override

    public void onBackPressed() {

        if (!isQuit) {

            Toast.makeText(this,"再按一次退出程序", Toast.LENGTH_SHORT).show();

            isQuit =true;

            //这段代码意思是,在两秒钟之后isQuit会变成false

            new Thread(()->{

                try {

                    Thread.sleep(2000);

                  }catch (InterruptedException e) {

                        e.printStackTrace();

                  }finally {

                        isQuit =false;

                  }

            }).start();

        }else {

            System.exit(0);

        }

    }

    方法2

    private long firstTime =0;

    @Override

    public boolean onKeyDown(int keyCode, KeyEvent event) {

    long secondTime = System.currentTimeMillis();

    if (keyCode == KeyEvent.KEYCODE_BACK) {

    if ( secondTime -firstTime <2000) {

    System.exit(0);

    }else {

    Toast.makeText(HomeActivity.this,"再按一次退出程序", Toast.LENGTH_SHORT).show();

    firstTime = System.currentTimeMillis();

    }

    return true;

    }

    return super.onKeyDown(keyCode, event);

    }

    相关文章

      网友评论

          本文标题:2020-07-29Android连点2次back键退出

          本文链接:https://www.haomeiwen.com/subject/ggqkrktx.html