看了下AppWidgetProvider的源代码。它继承自BroadcastReceiver,说明是一个广播接收者。
先上源代码:
public class AppWidgetProvider extends BroadcastReceiver { public AppWidgetProvider() { } // BEGIN_INCLUDE(onReceive) public void onReceive(Context context, Intent intent) { // Protect against rogue update broadcasts (not really a security issue, // just filter bad broacasts out so subclasses are less likely to crash). String action = intent.getAction(); if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { Bundle extras = intent.getExtras(); if (extras != null) { int[] appWidgetIds = extras.getIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS); if (appWidgetIds != null && appWidgetIds.length > 0) { this.onUpdate(context, AppWidgetManager.getInstance(context), appWidgetIds); } } } else if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) { Bundle extras = intent.getExtras(); if (extras != null && extras.containsKey(AppWidgetManager.EXTRA_APPWIDGET_ID)) { final int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID); this.onDeleted(context, new int[] { appWidgetId }); } } else if (AppWidgetManager.ACTION_APPWIDGET_ENABLED.equals(action)) { this.onEnabled(context); } else if (AppWidgetManager.ACTION_APPWIDGET_DISABLED.equals(action)) { this.onDisabled(context); } } // END_INCLUDE(onReceive) public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { } public void onDeleted(Context context, int[] appWidgetIds) { } public void onEnabled(Context context) { } public void onDisabled(Context context) { } }
源码很简单,我们可以看到,它实现了BroadcastReceiver的onReceive方法,在这个方法中通过intent的action来区分不同的接收的广播事件。
当action为AppWidgetManager.ACTION_APPWIDGET_UPDATE时,会调用onUpdate回调方法;
当action为AppWidgetManager.ACTION_APPWIDGET_DELETED时,会调用onDeleted回调方法;
当action为AppWidgetManager.ACTION_APPWIDGET_ENABLED时,会调用onEnabled回调方法;
当action为AppWidgetManager.ACTION_APPWIDGET_DISABLED时,会调用onDisabled回调方法。
那么上面四种类型的广播又是什么时候发出的呢?因此,我写了个继承AppWidgetProvider的类,测试了一下。
测试代码如下:
public class NewsWidgetProvider extends AppWidgetProvider { private final static String TAG = "NewsWidgetProvider"; @Override public void onDeleted(Context context, int[] appWidgetIds) { Log.d(TAG , "onDeleted"); super.onDeleted(context, appWidgetIds); } @Override public void onDisabled(Context context) { Log.d(TAG , "onDisabled"); super.onDisabled(context); } @Override public void onEnabled(Context context) { Log.d(TAG , "onEnabled"); super.onEnabled(context); } @Override public void onReceive(Context context, Intent intent) { Log.d(TAG , "onReceive"); super.onReceive(context, intent); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { Log.d(TAG , "onUpdate"); super.onUpdate(context, appWidgetManager, appWidgetIds); for(int id : appWidgetIds) Log.d(TAG , "appWidgetId=" + id); } }
实验结果为:
当第一个widget被创建出来时,执行顺序是:
当第二个相同的widget被创建出来时,执行顺序是:
当第三个相同的widget被创建出来时,执行顺序是:
删除一个widget时,执行顺序为:
删除最后一个widget时,执行顺序为: