为什么当我停止定时器时,我的安卓活动会崩溃?

huangapple go评论68阅读模式
英文:

Why does my Timer crashes my android activity when I stop it?

问题

我正在尝试制作一个切换按钮可以停止和重新启动计时器Timer),在我添加了一个名为 "Set_BPM" 的新方法之后它的工作正常它能够正确启动和停止但在我在停止后尝试重新启动它时崩溃了

**这是我在其中使用计时器的类**

    public class Metronome {

    int miliseconds;
    Timer timer = new Timer();

    public Metronome () { }

    public void Set_BPM (int bpm) {
        miliseconds = (60000 / bpm);
    }

    public void Start (final Context context) {
        TimerTask timerTask = new TimerTask () {
            @Override
            public void run() {
                Sonidos.Tick(context);
            }
        };
        timer.schedule(timerTask, 1000, miliseconds);
    }
    public void Stop () {
        timer.cancel();
        timer.purge();
    }
    }

这是我如何调用它的方式

    public void Encender_Metronomo (View view) {
        if (tb_metronome.isChecked()) {
            metronome.Set_BPM(Integer.parseInt(et_bpm.getText().toString()));
            metronome.Start(this);
        }
        else
            metronome.Stop();

        Sonidos.Button(this);
    }

**此外在我的 Activity 顶部还有这个对象**

    private Metronome metronome = new Metronome();

为什么当我停止定时器时,我的安卓活动会崩溃?

英文:

I'm trying to make a toggle button that can stop and replay a Timer, it worked just fine until I added a new method called "Set_BPM".
It starts and it stops correctly, it crashes when I try to start it again after I stopped it.

This is the class where I'm using the Timer:

public class Metronome {
int miliseconds;
Timer timer = new Timer();
public Metronome () { }
public void Set_BPM (int bpm) {
miliseconds = (60000 / bpm);
}
public void Start (final Context context) {
TimerTask timerTask = new TimerTask () {
@Override
public void run() {
Sonidos.Tick(context);
}
};
timer.schedule(timerTask, 1000, miliseconds);
}
public void Stop () {
timer.cancel();
timer.purge();
}
}

And this is how I'm calling it:

public void Encender_Metronomo (View view) {
if (tb_metronome.isChecked()) {
metronome.Set_BPM(Integer.parseInt(et_bpm.getText().toString()));
metronome.Start(this);
}
else
metronome.Stop();
Sonidos.Button(this);
}

There's also this object on top of my Activity:

private Metronome metronome = new Metronome();

为什么当我停止定时器时,我的安卓活动会崩溃?

答案1

得分: 0

一旦您调用cancel()方法取消了一个Timer,您将无法再安排更多的任务在其上。引用文档

> 一旦定时器被终止,它的执行线程将会优雅地终止,而且无法再在其上安排更多任务。

英文:

Once you cancel() a Timer, you cannot schedule more tasks with it. Quoting the documentation:

> Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it.

huangapple
  • 本文由 发表于 2020年10月17日 06:42:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/64397310.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定