android中Activity实现再按一次退出

Exit exit = new Exit();
    
  @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
      if (keyCode == KeyEvent.KEYCODE_BACK) {
              pressAgainExit();
              return true;
              }

        return super.onKeyDown(keyCode, event);
    }
  
  private void pressAgainExit() {
          if (exit.isExit()) {
              finish();
          } else {
              Toast.makeText(getApplicationContext(), "再按一次退出程序",
                      1000).show();
              exit.doExitInOneSecond();
          }
      }
辅助类Exit.java
package com.chen.b;

import android.os.Handler;
import android.os.HandlerThread;

public class Exit {

    private boolean isExit = false;
        private Runnable task = new Runnable() {
            @Override
            public void run() {
                isExit = false;
            }
        };
     
        public void doExitInOneSecond() {
            isExit = true;
            HandlerThread thread = new HandlerThread("doTask");
            thread.start();
            new Handler(thread.getLooper()).postDelayed(task, 1000);
        }
         
        public boolean isExit() {
            return isExit;
        }
     
        public void setExit(boolean isExit) {
            this.isExit = isExit;
        }
    }
posted @ 2012-06-22 15:33  安卓吧  阅读(1203)  评论(3编辑  收藏  举报