简体   繁体   English

停止和启动计时器

[英]Stop and start timer

Sorry for my english. 对不起我的英语不好。 I have timer and i wand if i click timer is on if i click again timer off. 我有计时器,如果我单击计时器,我会发出魔杖,如果我再次单击,则计时器关闭。 But my timer on only one time. 但是我的计时器只有一次。 If i click again(off timer) i have exception like this: 如果我再次单击(关闭计时器),则会出现如下异常:

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$1.onClick(ConnectDevice.java:153)
    at android.view.View.performClick(View.java:4240)
    ...

I dont know why its not work, please help. 我不知道为什么它不起作用,请帮助。 Below my class 在我班下

My 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();
}

Change onClick logic as follows (because in your case at the first time only executed callAsynchronousTask() and stopTimer(). so it raises exception at next onClick) 如下更改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;
                }
            }
        });

and doAsynchronousTask make it as field and cancel task on stopTimer(). 和doAsynchronousTask使其成为字段,并在stopTimer()上取消任务。

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

then it works fine. 然后就可以了

From Javadocs: 从Javadocs:

cancel() : Terminates this timer, discarding any currently scheduled tasks. cancel():终止此计时器,放弃任何当前计划的任务。 [...] Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it. [...]计时器终止后,其执行线程将正常终止,并且无法在其上安排更多任务。

and

schedule(Task task, long delay) 时间表(任务任务,长时间延迟)
throws: 抛出:
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated. IllegalStateException-如果任务已被调度或取消,计时器被取消或计时器线程终止。

So basically, your class tells you that it cannot complete the set task due to the fact that the timer has been cancelled. 因此,基本上,您的类告诉您,由于计时器已取消,它无法完成设置任务。 Something you could try is to make the timer sleep until the button is pressed again, instead of cancelling it completely. 您可以尝试使计时器进入睡眠状态,直到再次按下该按钮,而不是完全取消它。

Once you cancel the timer; 一旦取消计时器; you cannot start it again because thread is stopped. 您无法再次启动它,因为线程已停止。
See the link: 看到链接:
Pause the timer and then continue it 暂停计时器,然后继续
You have to maintain the state somehow and recreate timer with the current value 您必须以某种方式维护状态并使用当前值重新创建计时器

You need an async task it is a class so you can extend it. 您需要一个异步任务,它是一个类,因此您可以对其进行扩展。 Public class callAsynchronousTask extends async task And GetMsgs performBackgroundTask = new GetMsgs(); 公共类callAsynchronousTask扩展了异步任务,并且GetMsgs performBackgroundTask = new GetMsgs(); // PerformBackgroundTask this class is the class that extends Async Taskbar goes into the do in background method // PerformBackgroundTask此类是扩展Async Taskbar的类,它在后台方法中执行

Initialize your timer object inside callAsynchronousTask as shown below. 如下所示在callAsynchronousTask中初始化您的计时器对象。

public void callAsynchronousTask() { final Handler handler = new Handler(); 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
}

Also modify your in block because it is executing both if condition . 还要修改in块,因为它同时执行两个if条件。

Use boolean flag instead of int 使用布尔标志而不是int

 boolean isTimerRunning;

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM