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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With