Tomislav Markovski
Tomislav Markovski

Reputation: 12366

Widget update results in ANR

I have a simple app that reads internet resource and displays the information in a widget or in listview activity in form of imageviews and textviews. In addition to downloading the data from internet it also shows it in widget in a ViewFlipper.

When I add the widget to the home screen, it fires onUpdate immediately, downloads the data from internet and updates the widget. This works just fine. Log shows onUpdate and dataDownloaded with about 3 sec apart. On the next update (phone has gone to sleep mode), the update doesn't happen and this is what my logs report.

I'm looking for a possible solution to this. I was thinking about calling all the downloads in a different thread (from within the AppWidgetProvider, possibly using AsyncTask), store data in SQLite or local storage and doing the widget update (no downloads, just reading the data from SQLite and local storage) on the next onUpdate call. This would make the application/widget process more responsive and not fault into ANR.

Is this threading approach a bad practice? Is there an alternative? Should I use service instead? I'm inclined not to use a service, unless there's a lot of pros for it.

Sorry for the wall of text :)

Edit: From the docs http://developer.android.com/guide/practices/design/responsiveness.html

Android will display the ANR dialog for a particular application when it detects one of the following conditions:

Upvotes: 2

Views: 486

Answers (3)

ramdroid
ramdroid

Reputation: 6798

Using IntentService and a database backend is the proper way to do it I guess.

But what you never should do is performing such background tasks when the application is not active. Please only download data if your app is in foreground!

As for the widget you should use the "updatePeriodMillis" attribute. The Android system makes sure this is only executed when the widget is visible.

For more hints look at the usual location:

http://developer.android.com/guide/topics/appwidgets/index.html

Upvotes: 2

dave.c
dave.c

Reputation: 10918

If you are performing a network request then you need to do so either within an AsyncTask or in a Thread/Handler combination. Here are some links to help:

Upvotes: 2

Graham Borland
Graham Borland

Reputation: 60711

Threading is the only way to safely do network access on Android. So, yes, you'll need to use something like an ASyncTask or IntentService. Note that a plain Service won't be much help, since that runs on the main thread.

Upvotes: 2

Related Questions