Just to chime in, I was having exactly the same issue. I did a little searching online and found some info on this. Apparently the actual task being run needs to be run in a android.os.Handler to work properly. I also found some other issues with the overall architecture when this is implemented properly.
Here are the changes I made, all within EarthquakeService:
Change:
Code:
private TimerTask doRefresh = new TimerTask() {
public void run() {
refreshEarthquakes();
}
};
to:
Code:
private Handler handler = new Handler();
myTimerTask doRefresh = null;
public class myTimerTask extends TimerTask {
private Runnable runnable = new Runnable() {
public void run() {
try {
refreshEarthquakes();
} catch(Exception e) {
Log.e(">>>> Error executing refreshEarthquakes: " ,
e.getMessage());
}
}
};
public void run() {
handler.post(runnable);
}
}
In onStartCommand(), change:
Code:
updateTimer.cancel();
if (autoUpdate) {
updateTimer = new Timer("earthquakeUpdates");
updateTimer.scheduleAtFixedRate(doRefresh, 0, updateFreq*60*1000);
}
to:
Code:
if (doRefresh != null) {
doRefresh.cancel();
}
doRefresh = new myTimerTask();
updateTimer.cancel();
if (autoUpdate) {
updateTimer = new Timer("earthquakeUpdates");
updateTimer.scheduleAtFixedRate(doRefresh , 0 ,
updateFreq * 60 * 1000);
The basic change is adding the Handler.post() call. I found that if you don't call cancel() on the Timer
and TimerTask explicitly, an exception will be thrown. It seems odd to me that the Timer class doesn't cancel it's TimerTasks when you can cancel() on it considering that, according to the documentation here
http://developer.android.com/referen...l#cancel%28%29, it should.
If someone knows of a cleaner, more efficient way of doing this, I'm all ears. This is the type of thing that makes me love using Python as this seems so overly complicated for what you are actually doing, unless there is a better way of doing this...