我正在为任务列表应用程序实现小部件。每隔一段时间更新小部件并没有什么意义,所以每当用户添加或删除任务时,我都会尝试更新小部件:
private void updateWidget() {
Intent intent = new Intent(mContext, WidgetProvider.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
int ids[] = AppWidgetManager.getInstance(mContext).getAppWidgetIds(
new ComponentName(mContext, WidgetProvider.class));
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
mContext.sendBroadcast(intent);
}
这是 WidgetProvider 类的 onUpdate 方法(唯一被覆盖的方法):
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
if (appWidgetIds != null) {
for (int i = 0; i < appWidgetIds.length; i++) {
Intent intent = new Intent(context, WidgetService.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
RemoteViews widget = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
widget.setRemoteAdapter(appWidgetIds[i], R.id.widget_listview, intent);
appWidgetManager.updateAppWidget(appWidgetIds[i], widget);
}
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
WidgetService 类的 onGetViewFactory 方法:
@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return new TaskViewsFactory(getBaseContext());
}
以及清单的相关部分:
<receiver
android:name="com.nick.android.todo.widget.WidgetProvider"
android:enabled="true"
android:exported="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/widget_provider" />
</receiver>
<service
android:name="com.nick.android.todo.widget.WidgetService"
android:enabled="true"
android:permission="android.permission.BIND_REMOTEVIEWS" />
如果我删除小部件并将其添加到主屏幕,则列表将正确填充。添加任务有时会随机工作,但我无法弄清楚为什么/为什么不。
编辑:似乎我的 WidgetService.onGetViewFactory() 并不总是被调用。(小部件会在更新时更新)