我有一个带有配置活动的app小部件,我想在单击活动中的OK按钮时触发小部件的更新。我写了这段代码:
Intent initialUpdateIntent=new Intent(AppWidgetManager.
ACTION_APPWIDGET_UPDATE);
initialUpdateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
widgetID);
sendBroadcast(initialUpdateIntent);
但由于某种原因,没有调用onUpdate函数!有谁知道问题可能是什么? 感谢。
答案 0 :(得分:14)
尝试以下方法:
public static void updateWidgets(Context context) {
Intent intent = new Intent(context.getApplicationContext(), DayActivitiesAppWidget.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
// Use an array and EXTRA_APPWIDGET_IDS instead of AppWidgetManager.EXTRA_APPWIDGET_ID,
// since it seems the onUpdate() is only fired on that:
AppWidgetManager widgetManager = AppWidgetManager.getInstance(context);
int[] ids = widgetManager.getAppWidgetIds(new ComponentName(context, DayActivitiesAppWidget.class));
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
widgetManager.notifyAppWidgetViewDataChanged(ids, android.R.id.list);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
context.sendBroadcast(intent);
}
以这种方式将DayActivitiesAppWidget替换为您的AppWidgetProvider
类,更新所有窗口小部件实例,然后您可以通过更新单个窗口小部件实例来追踪问题。
答案 1 :(得分:1)
您是否尝试在onReceive中捕获您的广播信息:
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
String strAction = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(strAction)) {
/* Do update */
}
}
否则,IMO最好定义自己的Message,而不是使用ACTION_APPWIDGET_UPDATE清楚显示小部件更新视图的逻辑,如清单文件中的1.Declare意图名称:
<action android:name="com.yourdomain.youapp.SETTING_UPDATE" />
2.定义意图名称:
public static final String SETTING_UPDATE = "com.yourdomain.youapp.SETTING_UPDATE";
3.Handle in onReceive:
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
String strAction = intent.getAction();
if (SETTING_UPDATE.equals(strAction)) {
/* Do update setting */
}
}
希望它有所帮助^^