android連續按兩次返回退出程序(完整代碼)

UserHelperjava

package com.hk.icie;  
  
public class UserHelper {  
      
    private static Boolean isExit = false;  
  
    public static Boolean getIsExit() {  
        return isExit;  
    }  
  
    public static void setIsExit(Boolean isExit) {  
        UserHelper.isExit = isExit;  
    }  
}

ExitTimerTaskide

package com.hk.utils;  
  
import java.util.TimerTask;  
  
import com.hk.icie.UserHelper;  
  
public class ExitTimerTask extends TimerTask {  
    @Override  
    public void run() {  
        UserHelper.setIsExit(false);  
    }  
}

Tab1Activitythis

// 此部分爲了實現按兩下返回退出  
private Timer tExit = new Timer();  
private ExitTimerTask exitTimerTask = new ExitTimerTask();  
  
@Override  
public boolean onKeyDown(int keyCode, KeyEvent event) {  
    if (keyCode == KeyEvent.KEYCODE_BACK) {  
        if (!UserHelper.getIsExit()) {  
            UserHelper.setIsExit(true);  
            AlertUtils.ToastAlert(Tab1Activity.this, R.string.alert_exit);  
            if (tExit != null) {  
                if (exitTimerTask != null) {  
                    // 將原任務從隊列中移除(必須的,不然報錯)  
                    exitTimerTask.cancel();  
                }  
                // 新建一個任務  
                exitTimerTask = new ExitTimerTask();  
                tExit.schedule(exitTimerTask, 2*1000);  
            }  
        }  
        else {  
            UserHelper.setIsExit(false);  
            finish();  
            System.exit(0);  
        }  
    }  
    return true;  
}

須要注意的是每次放定時任務前,確保以前任務已從定時器隊列中移除,每次聽任務都要新建一個對象,不然出現一下錯誤:ERROR/AndroidRuntime(11761): java.lang.IllegalStateException: TimerTask is scheduled already,同一個定時器任務只能被放置一次。code

相關文章
相關標籤/搜索