Note: This is all in updateAppWidget() of my AppWidgetProvider.
I'm trying to have my widget blink back and forth between 2 colors forever. This is done by having the delayed runnables post another delayed runnable to the handler, which itself posts another... and so on. But could there be potential memory problems from doing it this way? The widget runs with no problems, but then a few hours later there's a chance it freezes or starts blinking erratically. Are these symptoms obviously because of my implementation? (mainly using "this" in postDelayed())
final int blinkDelay = 1000;
final Handler myHandler = new Handler();
final Runnable runnable = new Runnable() {
boolean lightOn = true;
public void run() {
if (lightOn){
lightOn = false;
views.setInt(R.id.RelativeLayout1, "setBackgroundColor", Color.argb(150, 255, 248, 231)); //turn light "off"
appWidgetManager.updateAppWidget(appWidgetId, views);
myHandler.postDelayed(this, blinkDelay);
} else{
lightOn = true;
views.setInt(R.id.RelativeLayout1, "setBackgroundColor", Color.argb(220, 255, 248, 231)); //turn light "on"
appWidgetManager.updateAppWidget(appWidgetId, views);
myHandler.postDelayed(this, blinkDelay);
}
}
};
//start the blink loop
myHandler.post(runnable);
The rest of the overriden methods are unchanged.
You need to make sure in onDestroy you remove all runnables from the handler, or you could cause a memory leak (basically you need to assure it eventually ends the loop). But that general pattern is standard.