我正在为任务列表应用程序实现一个小部件。在一个时间间隔内更新窗口小部件并没有多大意义,因此每当用户添加或删除任务时我都会尝试更新窗口小部件:
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());
}
Manifest的相关部分:
<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()。 (小部件在更新时会更新)
答案 0 :(得分:3)
我终于明白了。
小部件确实正在更新,但具有相同的项目。我需要覆盖onDataSetChanged()以获取新的项目列表并调用notifyAppWidgetViewDataChanged:
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.widget_listview);