I need to subscribe to database changes using an Observer
in an app widget. The documentation says the right place for such setup is onEnabled()
in AppWidgetProvider
. But, onEnabled()
is only called when a new widget is added. If the app is started up and the widget is already there, it doesn't get called and the data in the widget doesn't update. Should I send ACTION_APPWIDGET_ENABLED
broadcast on app startup or there is another way of doing this?
Asked
Active
Viewed 1,403 times
0

Yulia Rogovaya
- 924
- 1
- 8
- 26
2 Answers
2
I need to subscribe to database changes using an Observer in an app widget.
That is not possible, unless you are going to run an everlasting service, which is not a good design pattern.
If this is your own database, simply push updates to your app widget using AppWidgetManager
when you change your database contents.

CommonsWare
- 986,068
- 189
- 2,389
- 2,491
-
Why this is not possible? This is done in WeatherListWidget sample for API 14,15 using RemoteViewsService. – Yulia Rogovaya May 17 '12 at 14:14
-
1@YuliaRogovaya: "Why this is not possible?" -- an `AppWidgetProvider` is not a `Service`. It is a `BroadcastReceiver`. An instance of `AppWidgetProvider` will live for milliseconds and cannot do anything itself that will live past methods like `onUpdate()`, such as registering an `Observer`. IMHO `WeatherListWidget` is a very broken sample, which I will try to work with Google to fix. – CommonsWare May 17 '12 at 14:20
-
In this sample a static observer is registered in onEnabled(). When onChange() for this observer is called on a worker thread, it pushes RemoteViewsService to update the widget. The problem is, onEnabled() is only called when a widget is added. If the app starts up and the widget is already there, initialization doesn't go through... – Yulia Rogovaya May 17 '12 at 14:29
-
From the documentation to onEnabled(): "If you need to open a new database or perform other setup that only needs to occur once for all App Widget instances, then this is a good place to do it." – Yulia Rogovaya May 17 '12 at 14:29
-
2@YuliaRogovaya: And as soon as the process ends, the observer goes away. That may happen within milliseconds of `onEnabled()` being called. As I wrote, IMHO, this is a very broken sample. – CommonsWare May 17 '12 at 14:30
-
Thank you for your response and explanations! – Yulia Rogovaya May 17 '12 at 14:41
0
Though CommonsWare is right in his answer above that the approach of keeping a static observer for an app widget is flawed, to fix the problem in the realization I already had, I send ACTION_APPWIDGET_ENABLED broadcast on app startup. Not a very clean way, but it works.

Yulia Rogovaya
- 924
- 1
- 8
- 26