开发者

Why is AppWidgetProvider created each time I add an app widget?

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 o开发者_StackOverflow社区nUpdate(..., 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?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜