Search code examples
androidbootrebootcontentobserverandroid-appwidget

Register content observer for appwidgets on boot


I am registering a ContentObserver when the user adds my appwidget to the home screen. The intended behavior is that changes to the underlying data in my ContentProvider will trigger my appwidget to update. The problem is if the user then reboots the device, I no longer have a ContentObserver registered.

Android's AppWidget framework appears to provide no hooks to do any sort of setups after the device boots, so I can't register another ContentObserver on the data. The only solution I can think of is creating a BroadcastReceiver, registered in the manifest, that receives the BOOT_COMPLETED action. I was hoping not to have to do this though.

Are there any ways to register a ContentObserver (or do any other setup related to AppWidgets) after boot so that existing appwidgets will continue to function properly across device reboots? (If possible, is there a sample of this somewhere?)

EDIT:

It appears after boot my AppWidgetProvider is being called, and the onEnabled and onUpdate callbacks both occur. It starts my AppWidgetService and creates a RemoteViewsFactory -- at which point I should have a ContentObserver registered.

For whatever reason though, the ContentObserver is not firing when the data in my ContentProvider changes. I can't figure out why.


Solution

  • EDIT

    This answer is a bit outdated. Making a Service solely for holding a ContentObserver is a bit heavy handed and users might find it strange that an app is keeping a service around without understanding why. Also the OS can terminate the Service, which leaves you without a ContentObserver.

    It's probably better to force refresh your appwidgets yourself when you data changes. Google does this as well in their iosched app:

    // Widgets can't register content observers so we refresh widgets separately.
    context.sendBroadcast(ScheduleWidgetProvider.getRefreshBroadcastIntent(context, false));
    

    Source: ScheduleProvider ScheduleWidgetProvider

    ORIGINAL ANSWER

    I've solved my own problem by creating a new Service class. I start the service in my AppWidgetProvider's onEnabled() callback and stop the service in the onDisabled() callback. The content observer is registered in the Service's onCreate() and unregistered in onDestroy.

    This approach lets all my appwidgets be updated when the underlying data changes and works through device reboot.