尝试计划计时器时出现IllegalStateException

时间:2017-04-10 13:31:21

标签: java android

取消方法的文档:

  

(松散地说,如果它阻止一个或多个预定的执行发生,则此方法返回true。)

当我执行此代码时:

private Timer timer = null;
private TimerTask runnable = new TimerTask() {
    @Override
    public void run() {
        Log.e("DEBUG", "Scheduled task tick");
        if(!looper){
            Looper.prepare();
            looper = true;
        }
        VolleyConnect vc = new VolleyConnect();
        vc.connect(ErrorListActivity.this);
    }
};

@Override
public void onWindowFocusChanged(boolean focus){
    if(!focus){
        kill();
    }else{
        start();
    }
    Log.e("DEBUG", "FOCUS " + focus);
}

public void start(){
    if(timer == null){
        timer = new Timer();
        //180000 ms = 3 minutes
        timer.scheduleAtFixedRate(runnable, 0L, 180000L);<--- This line is the one that triggers the error.
    }
}

public void kill(){
    if(timer != null) {
        boolean rep = runnable.cancel();
        Log.e("DEBUG", "REP = " + rep);
        timer.cancel();
        timer = null;
        looper = false;
    }
}

出乎意料的是,debug语句打印出来:

E/DEBUG: REP = true

表示取消应该完成。但是,当我重新获得窗口焦点(并尝试重新安排计时器)时,应用程序崩溃时出现此错误:

java.lang.IllegalStateException: Task already scheduled or cancelled
    at java.util.Timer.sched(Timer.java:401)
    at java.util.Timer.scheduleAtFixedRate(Timer.java:328)
    at com.package.ErrorListActivity.start(ErrorListActivity.java:198)
    at com.package.ErrorListActivity.onWindowFocusChanged(ErrorListActivity.java:189)
    at android.support.v7.view.WindowCallbackWrapper.onWindowFocusChanged(WindowCallbackWrapper.java:128)
    at android.support.v7.view.WindowCallbackWrapper.onWindowFocusChanged(WindowCallbackWrapper.java:128)
    at com.android.internal.policy.DecorView.onWindowFocusChanged(DecorView.java:1414)
    at android.view.View.dispatchWindowFocusChanged(View.java:10173)
    at android.view.ViewGroup.dispatchWindowFocusChanged(ViewGroup.java:1192)
    at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:3757)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6120)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

我不知道如何解决这个问题,我已经查看了其他类似的问题,但还没有任何工作。有什么想法吗?

<子> 顺便说一下,这不是this question的副本。这是同一个问题,但我调用了取消,它返回true(意味着它应该工作,但它没有)。

1 个答案:

答案 0 :(得分:5)

您可以重复使用timertask。创建TimerTask的新实例。