I found the code pasted below in a post on this forum back in 2011. I was using a timer to trigger the execution of doSomeWork but doSomeWork spawns an asynctask and (as I found out) asynctasks can only be spawned from the UI thread. So, I converted to using this postDelayed function of a Handler.
Now this code does indeed call doSomeWork every ten seconds and my asynctask no longer has problems. But when I call stopRepeatingTask() it does NOT stop the execution of doSomeWork - it keeps getting called every ten seconds.
This code is in a service and stopSelf() has been called but the code keeps running. The Android system doesn't even show the service as running but it's still calling doSomeWork.
What's wrong? How can I stop it? Thanks, Gary
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
}