简体   繁体   中英

How to update widget from app?

I have an app which downloads a timetable and saves it, it also regularly downloads changes to this timetable. I'm currently using a singleton, but I find this ugly from a design perspective. Because of the downloads I need a centralized system to minimize network usage.

In the current situation, every class that requires updates from the singleton first gets an instance of this singleton and then provides an interface of which certain methods are called when an update is required. Currently the singleton handles all of the downloads in worker threads. Normally I would use an AsyncTask, called from the Activity, however because I have to send the result to the widget too, I can't see this work.

The alternative is using a Service. I would simply bind to it from both the widget and the activity. The problem in this case is that I can't bind from a BroadcastReceiver (which an AppWidgetProvider is). The issue would be that I can't regularly update my widget.

My question is: how can I (or: can I) design my app in such a way that I can update my widget from a service (in order to get rid of the singleton) or is there a better way (maybe BroadcastReceivers)?

how can I (or: can I) design my app in such a way that I can update my widget from a service (in order to get rid of the singleton) or is there a better way (maybe BroadcastReceivers)?

To update an app widget, call updateAppWidget() on an AppWidgetManager . This can be done at any point, not just from an AppWidgetProvider .

To update an app widget on a periodic basis, either use android:updatePeriodMillis in your app widget metadata, or set up AlarmManager directly yourself. In either case, you would want to delegate the work to an IntentService , as "downloads a timetable" is not something you want to do on the main application thread -- IntentService gives you a background thread and automatically stops itself when your work is complete, so you do not take up RAM except when you are actively doing work.

To do work in general on a periodic basis, use AlarmManager and an IntentService . The IntentService can, as part of its work, update app widgets, if desired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM