【发布时间】:2012-05-05 20:49:12
【问题描述】:
以下是我的代码:
在 MainActivity.class 中
private OnCheckedChangeListener alert_on_off_listener = new OnCheckedChangeListener(){
public void onCheckedChanged(RadioGroup groupname, int CheckedButtonId) {
if(CheckedButtonId==R.id.radiobutton_on){
Toast.makeText(getApplicationContext(), "radio on", Toast.LENGTH_LONG).show();
alert_on = true;
display_alert();
}
else{
alert_on = false;
}
}
};
public void display_alert(){
int delay = 10000;
Timer timer =new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
Intent myIntent = new Intent(HoraWatchActivity.this,MyService.class);
startService(myIntent);
}
}, delay,10000);
}
MyService.class
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
if(MainActivity.alert_on)
Toast.makeText(getApplicationContext(), "Alert is On", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "Alert is Off",Toast.LENGTH_LONG).show();
}
我正在检查onCheckedChangeListener并根据选中的单选按钮调用display_alert函数。
在 display_alert 函数中,我以 10 秒的固定速率使用定时器调度并调用 myservice 类。
所以一旦我检查了radio_on 按钮,它就会调用我的display_alert 函数并在吐司中显示“警报开启”。所以它工作正常。
如果我再次检查radio_off 按钮,然后检查radio_on 按钮,我会收到“警报开启”toast,但toast 会出现两次。同样,如果我再次选择radio_on 按钮,吐司将第三次显示,但我只需要一次。这是因为计时器每 10 秒运行一次。单击radio_off 按钮后,我想停止计时器。
问题是,一旦我启动了计时器,我就没有再停止它。我应该何时以及如何取消课堂上的定时器任务?
【问题讨论】:
标签: android service timer android-context timertask