使用Handler作为计时器但无法阻止它

时间:2013-09-12 22:47:33

标签: android multithreading handler

我发现下面的代码粘贴在2011年的论坛上。我使用计时器来触发doSomeWork的执行,但是doSomeWork会生成asynctask并且(我发现)asynctasks只能从UI中生成线。所以,我转换为使用Handler的postDelayed函数。

现在这段代码确实每十秒调用一次doSomeWork,而我的asynctask不再有问题。但是当我调用stopRepeatingTask()时,它不会停止doSomeWork的执行 - 它会每隔十秒钟调用一次。

此代码在服务中并且已调用stopSelf()但代码仍在运行。 Android系统甚至没有将服务显示为正在运行,但它仍在调用doSomeWork。

怎么了?我怎么能阻止它? 谢谢,加里

private int m_interval = 5000; // 5 seconds by default, can be changed later
private Handler m_handler;

@Override
protected void onCreate(Bundle bundle) {
  // ...
  m_handler = new Handler();
}

Runnable m_statusChecker = new Runnable() {
     @Override 
     public void run() {
          doSomeWork(); //this function can change value of m_interval.
          m_handler.postDelayed(m_statusChecker, m_interval);
     }
};

void startRepeatingTask() {
    m_statusChecker.run(); 
}

void stopRepeatingTask() {
    m_handler.removeCallbacks(m_statusChecker); //  <--this does not appear to work
}

1 个答案:

答案 0 :(得分:5)

在代码中添加状态以停止重新生成新任务:

private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;
private boolean mIsRunning;

protected void onCreate(Bundle bundle) {
  // ...
  mHandler = new Handler();
}

Runnable mStatusChecker = new Runnable() {
     @Override 
     public void run() {
          if (!mIsRunning) {
              return; // stop when told to stop
          }
          doSomeWork(); // this function can change value of mInterval.
          mHandler.postDelayed(mStatusChecker, mInterval);
     }
};

void startRepeatingTask() {
    mIsRunning = true;
    mStatusChecker.run();
}

void stopRepeatingTask() {
    mIsRunning = false;
    mHandler.removeCallbacks(mStatusChecker);
}