Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long-running operation to update an Android appwidget

I have a widget that needs to perform a potentially long-running operation in onUpdate(). Just performing the operation directly resulted in ANR's. To solve this, my first attempt was to create a thread therein. I noticed that the widget would not get updated in some cases. My guess here is that once onUpdate() exits, Android may kill the process along with the unfinished thread.

My next attempt was to create an intent service. The widget's onUpdate() just starts the intent service, which does the work directly and updates the widget when done. This works, but much to my surprise it appears that onHandleIntent() is single-threaded. If I have two widgets, and then both update and start the intent service, they update sequentially ...

The two widgets case is not really important, but I'm just wondering about a best practice for this type of pattern.

To solve the two widgets case I ended up updating all the widget instances with the same data whenever any one of them is clicked. e.g., I perform the long-running process once and apply the results to all the widget instances. In my scenario this doesn't matter, but for many widgets, it might be important not to do that.

Thoughts?

like image 490
Jeffrey Blattman Avatar asked Dec 14 '10 20:12

Jeffrey Blattman


1 Answers

but much to my surprise it appears that onHandleIntent() is single threaded

Yes.

if i have two widgets, and then both update and start the intent service, they update sequentially ...

Yes.

but i'm just wondering about a best practice for this type of pattern.

Your IntentService was a fine upstanding solution, IMHO. Remember that Android runs on slow CPUs, with devices with little RAM. Running lots of threads in parallel is generally not a good idea.

then i'm getting into starting a thread in onHandleIntent(), which requires a wake lock, and it just seems it's getting all too complicated.

Try my WakefulIntentService.

like image 138
CommonsWare Avatar answered Oct 10 '22 21:10

CommonsWare