How can I interrupt this alarm without exceptions?
I have an alarm that will play a sound at a specific time. I'm looking for a way to stop it from running, how can I do it?
This is my alarm's code :
waiter = new Thread(new Runnable() {
public void run() {
while (Thread.currentThread() == waiter) {
Calendar d = Calendar.getInstance();
if (getAlarmHours() == d.get(Calendar.HOUR_OF_DAY)) {
if (getAlarmMinutes() == d.get(Calendar.MINUTE)) {
UserInterface
开发者_Go百科 .setAlarmText("no alarms");
playSound.play();
isSoundPlaying = true;
break;
}
}
}
}
});
I'd like to re-use the alarm again, any suggestions on where I might be going wrong would be appreciated. If I use wait()
, how can I notify without getting exceptions?
waiter.interrupt();
also, inside your while loop, maybe put a Thread.sleep(100);
I have written some fictional code that should help . code you can modify the solution to look like your program if that is what you wish
Consider moving your code from a while loop to some form of a Timer.
Some common recommendations will be the Timer class build into the JVM or Quartz which is a 3rd party library from Terracotta.
For an example of your alarm problem using standard JVM options
Timer timer = new Timer();
//Start the alarm now, change the date object to your specific time
timer.schedule(new AlarmTimerTask(), new Date(System.currentTimeMillis()));
And your AlarmTimerTask Class would be
public class AlarmTimerTask extends TimerTask {
public void run(){
//Do something
}
}
if at any point you want to remove the timer (shut it off or app is closing) call timer.cancel()
to remove the task.
Quartz will provide you with added functionality and a good library to learn
Edit: I should point out that if you assign the AlarmTimerTask class to its own variable instead of initializing it in the schedule() method, you can call cancel() on the individual task as well, and not just the Timer
精彩评论