android程序 点击两次返回键程序退出(方法总结)

方法一、
private static Boolean isExit = false;  
    private static Boolean hasTask = false;  
    Timer tExit = new Timer();  
    TimerTask task = new TimerTask() {  
@Override  
        public void run() {  
            isExit = false;  
            hasTask = false;  
        }  
    };  
public boolean onKeyDown(int keyCode, KeyEvent event) {  
                // TODO Auto-generated method stub  
                if(keyCode == KeyEvent.KEYCODE_BACK){  
//                        System.out.println("user back down");  
                        if(!isExit) {  
                                isExit = true;  
                                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();  
                                if(!hasTask) {  
                                        tExit.schedule(task, 2000);  //两秒之内若不按返回键,将isExit恢复为false
                                }
 } else {//  isExit=true
                                finish();  
                                System.exit(0);  
                        }  
                }                          
                return false;  
        }  

---------------------------------------------------------------------------------------------------------------------------------------------

方法二、

boolean isExit=false;  
    Handler mHandler = new Handler(){  
        @Override 
        public void handleMessage(Message msg) {  
            super.handleMessage(msg);  
            isExit=false;  
        }  
          
    };  
      
    @Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) {  
        // TODO Auto-generated method stub 
        if(keyCode == KeyEvent.KEYCODE_BACK){  
            if(!isExit){  
                isExit=true;  
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();  
                //利用handler延迟发送更改状态信息 
                mHandler.sendEmptyMessageDelayed(0, 2000);  
            }  
            else{  
                finish();  
                System.exit(0);  
            }  
        }  
        return false;  
    } 


--------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

方法三、        

private long mExitTime = 0;
        public boolean onKeyDown(int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                        if ((System.currentTimeMillis() - mExitTime) > 2000) {
                                Object mHelperUtils;
                                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                                mExitTime = System.currentTimeMillis();

                        } else {
                                finish();
                        }
                        return true;
                }
                return super.onKeyDown(keyCode, event);
        }
}

你可能感兴趣的:(android)