2
我正在爲任務列表應用程序實現小部件。它並沒有真正意義的更新部件上的間隔,所以我想無論用戶添加或刪除任務,例如更新插件:Android AppWidget onUpdate並不總是更新小部件
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()並不總是被調用。 (這些小部件在更新時會更新)
是當你每次發送Brooadcast的onUpdate()叫什麼名字? –
@GopalRao是的。 –