Android连续点击两次Back键退出程序

第一个方法

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

第二个方法


private boolean isQuit = false;

@Override
public void onBackPressed() {
   
   if (!isQuit) {
       Toast.makeText(HomeActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
       isQuit = true;

       //这段代码意思是,在两秒钟之后isQuit会变成false
       new Thread(new Runnable() {
           @Override
           public void run() {
               try {
                   Thread.sleep(2000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               } finally {
                   isQuit = false;
               }
           }
       }).start();


   } else {
       System.exit(0);
   }
}

你可能感兴趣的:(Android连续点击两次Back键退出程序)