gpt4 book ai didi

java - 取消后如何重新创建 Timer 类对象?

转载 作者:可可西里 更新时间:2023-11-01 11:41:39 28 4
gpt4 key购买 nike

我正在制作一个 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com