views:

34

answers:

2

Hello guys'n'girls :)

I'm slighty puzzled about how android's AppWidget machinery works.

I reimplemented the AppWidgetProvider's constructor like this:

public class MyProvider extends AppWidgetProvider {

   public MyProvider() {
     Log.d("TEST", "Creating...")
   }

   public void onUpdate(..., int[] appWidgetIds) {
      // updating stuff here
   } 
}

From what I've read in the docs, I understood that AppWidgetProvider is instantiated once, when widget of that type is added for the first time. If another widget of the same type gets added, it will be managed by exactly that provider.

But I just discovered that this is not the case!

For each widget I add, android creates a new MyProvider (I see that from 'adb logcat' - it prints "Creating..." for each widget)! I don't understad why :) Maybe I got something wrong? Or documentation isn't clear on something. What's the reason of having appWidgetIds passed to onUpdate and other methods if each provider is managing only ONE widget?

A: 

AppWidgetManager is created only once. An AppWidgetProvider is created for each AppWidget that is created.

BrennaSoft
Thanks! it seems that the answer above is more detailed, so I'll mark it as accepted :)
dpimka
+2  A: 

AppWidgetProvider is a subclass of BroadcastReceiver. Quoting the BroadcastReceiver documentation:

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.

Hence, AppWidgetProviders are disposable and should be treated as such. Every app widget operation (update, etc.) will result in a provider being created, used, and discarded.

CommonsWare
Indeed. Thanks for explanation!
dpimka