我正在制作一个 Android 应用程序,它可以由用户在指定的时间间隔后打开/关闭闪光灯。它工作得很好,除了在第二次调用 .cancel() 方法后重新创建 Timer 对象时,它每次都会使应用程序崩溃。 这是初始化部分:
Timer timer; //variable of Timer class
TimerTask timerTask; //variable of TimerTask class
这是按下负责打开/关闭闪烁的按钮时调用的方法:
blink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
delay = Integer.valueOf(startDelay.getText().toString());
gap = Integer.valueOf(blinkDelay.getText().toString());
if(!isBlinking) { //isBlinking is a boolean to know whether to stop or re-start timer
timer = new Timer(); //I'm creating an object of Timer class every time.
isBlinking = true;
timer.schedule(timerTask, delay, gap);
}
else{
isBlinking = false;
stoptimertask(); //this will cancel the 'timer' and make it null.
}
}
});
上面代码中的“stoptimertask()”方法具有:
public void stoptimertask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
我正在通过下面所示的方法设置 TimerTask 类的“timertask”变量。在主 Activity 的 onCreate() 方法中调用:
public void initializeTimerTask() {
timerTask = new TimerTask() { //This is passed as the first argument to the timer.schedule() method
public void run() {//Basically turns on/off flash. Works well.
if(!state) {
turnOnFlash();
state = true;
}
else {
turnOffFlash();
state = false;
}
}
};
我的问题是,为什么当我第三次按下闪烁按钮时应用程序崩溃?
- 第一次按下时,isBlinking 为 false,因此 if block 执行创建 Timer 类的新对象并启动计时器。
- 当第二次按下时,将调用 stoptimertask() 来取消计时器并将计时器变量设置为 null。
- 当使用不同的延迟和间隙值第三次按下时,应该创建 Timer 类的新对象,但应用程序意外崩溃,并出现“不幸的是,应用程序已停止”错误。 我哪里错了?
最佳答案
您还必须进行清除。
timer.cancel();
timer.purge();
关于java - 取消Timer类对象后如何重新创建它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35945149/