如何停止计时器Android

Dra*_*ray 1 service android timer android-context timertask

以下是我的代码:

在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);
}
Run Code Online (Sandbox Code Playgroud)

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();
}
Run Code Online (Sandbox Code Playgroud)

我正在根据选中的单选按钮检查onCheckedChangeListener和调用display_alert功能.

display_alert功能中,我使用固定速率为10秒的定时器调度并调用myservice类.

所以一旦我检查了radio_on按钮,它就会调用我的display_alert函数并在吐司中得到"警告".所以它的工作正常.

如果我再次检查radio_off按钮然后检查radio_on按钮,我就会得到"警告"吐司,但吐司会来两次.同样,如果我再次选择radio_on按钮,吐司将第三次显示,但我只需要一次.这是因为计时器每10秒运行一次.我想点击radio_off按钮后停止计时器.

问题是,一旦我启动计时器,我没有进一步停止它.何时以及如何取消课程中的计时器任务?

Edu*_*rdo 9

首先,以单独的方式创建TimerTask:

class MyTimerTask extends TimerTask {
  public void run() {
    Intent myIntent = new Intent(HoraWatchActivity.this,MyService.class);
    startService(myIntent);
  }
}
Run Code Online (Sandbox Code Playgroud)

在某处声明它,当然可以在OnCheckedChangeListener中看到:

MyTimerTask myTimerTask;
Run Code Online (Sandbox Code Playgroud)

安排它:

public void display_alert() {
  int delay = 10000;  
  myTimerTask = new MyTimerTask();
  Timer timer = new Timer();
  timer.scheduleAtFixedRate(myTimerTask, delay, 10000);
}
Run Code Online (Sandbox Code Playgroud)

然后将代码修改为:

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{
         myTimerTask.cancel();
         alert_on = false;
     }   
}
};
Run Code Online (Sandbox Code Playgroud)