Reputation: 3089
I'm writing an Android widget. I have MyAppWidgetProvider which extends AppWidgetProvider.
During the widget's lifecycle, it gets various callbacks called on it: onUpdate, onEnabled, onDisabled, etc. They're triggered by actions ACTION_APPWIDGET_UPDATE, ACTION_APPWIDGET_ENABLED, etc.
According to the App Widget Guide, "[onDisabled] is where you should clean up any work done in onEnabled". I interpreted that to mean that onEnabled may set up some instance state in MyAppWidgetProvider, and onDisabled should tear it down. However, I'm finding that a new instance of MyAppWidgetProvider is created for every single action.
So, is this the expected behavior? Should I always expect a new instance to be created for every callback, or is there some way to configure the broadcast receiver or sender to use the existing instance? If a new instance is always created, then it's unsafe to store any instance state in MyAppWidgetProvider, which is not clear from the docs.
Upvotes: 1
Views: 255
Reputation: 5586
I am not very familiar with AppWidgetProvider but as it is a type of BroadcastReceiver then it is correct that a new instance should be spun up on each event. Processing in the BroadcastReceiver should be minimal. In this case solely to update the app widget with the information obtained from the new intent.
Upvotes: 1
Reputation: 38168
Yes, you can't hope to ahve a single instance of BroadcastReceiver beeing recycled.
The docs states that :
A BroadcastReceiver object is only valid for the duration of the call to
onReceive(Context, Intent). Once your code returns from this function, the system
considers the object to be finished and no longer active.
And as AppWidgetProvider extend BroadcastReceiver, you got your answer. :)
Upvotes: 2