停止和启动定时器

Stop and start timer

对不起我的英语。我有定时器,如果我再次点击定时器关闭,我会点击定时器。但我的计时器只开了一次。如果我再次点击(关闭计时器),我会遇到这样的异常:

E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Timer was canceled
    at java.util.Timer.scheduleImpl(Timer.java:561)
    at java.util.Timer.schedule(Timer.java:481)
    at installation.ConnectDevice.callAsynchronousTask(ConnectDevice.java:211)
    at installation.ConnectDevice.onClick(ConnectDevice.java:153)
    at android.view.View.performClick(View.java:4240)
    ...

我不知道为什么它不起作用,请帮助。在我下面 class

我的class

private Timer timer;
int time = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.i_connect_device);

    timer = new Timer();

    // my botton
    includeDevice.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (time < 1) {
                callAsynchronousTask();
                time++;
            }

            if (time > 0) {
                stopTimer();
                time--;
            }
        }
    });

}

public void callAsynchronousTask() {
    final Handler handler = new Handler();

    TimerTask doAsynchronousTask = new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    try {
                        Log.e("Timer is work", "Timer is work");
                        // GetMsgs performBackgroundTask = new GetMsgs();
                        // PerformBackgroundTask this class is the class
                        // that extends AsynchTask
                        // performBackgroundTask.execute();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, 1000 * 10); // execute in every
                                                        // 50000 ms
}

public void stopTimer() {
    timer.cancel();
}

来自 Javadocs:

cancel() : Terminates this timer, discarding any currently scheduled tasks. [...] Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it.

schedule(Task task, long delay)
throws:
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.

所以基本上,您的 class 告诉您由于计时器已被取消,它无法完成设置的任务。您可以尝试让计时器休眠直到再次按下按钮,而不是完全取消它。

取消定时器后;您无法再次启动它,因为线程已停止。
参见 link:
Pause the timer and then continue it
您必须以某种方式维护状态并使用当前值

您需要一个异步任务,它是一个 class 以便您可以扩展它。 Public class callAsynchronousTask 扩展异步任务 和 GetMsgs performBackgroundTask = new GetMsgs(); // PerformBackgroundTask 这个 class 是扩展 Async Taskbar 的 class 进入 do in background 方法

在 callAsynchronousTask 中初始化您的计时器对象,如下所示。

public void callAsynchronousTask() { final Handler handler = new Handler();

    TimerTask doAsynchronousTask = new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    try {
                        Log.e("Timer is work", "Timer is work");
                        //GetMsgs performBackgroundTask = new GetMsgs();
                        // PerformBackgroundTask this class is the class that extends AsynchTask
                        //performBackgroundTask.execute();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                    }
                }
            });
        }
    };
    timer=new Timer();
    timer.schedule(doAsynchronousTask, 0, 1000*10); //execute in every 50000 ms
}

同时修改您的 in 块,因为它同时执行 if 条件。

使用布尔标志而不是整数

 boolean isTimerRunning;

  if (!isTimerRunning) {
            callAsynchronousTask();
            isTimerRunning=true;
        }

       else (isTimerRunning) {
            stopTimer();
            isTimerRunning=false;
      }

更改onClick逻辑如下(因为在你的情况下第一次只执行了callAsynchronousTask()和stopTimer()。所以它在下一个onClick时引发异常)

btnTimer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (time == 0) {
                    callAsynchronousTask();
                    time = 1;
                } else {
                    stopTimer();
                    time = 0;
                }
            }
        });

和 doAsynchronousTask 将其作为字段并在 stopTimer() 上取消任务。

public void stopTimer() {
    doAsynchronousTask.cancel();
}

然后它工作正常。