Sending an update broadcast to an app widget

2020-07-13 07:40发布

I have an app widget with a configure activity, and I want to trigger an update to the widget when an OK button in the activity is clicked. I wrote this code:

            Intent initialUpdateIntent=new Intent(AppWidgetManager.
                    ACTION_APPWIDGET_UPDATE);
            initialUpdateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    widgetID);
            sendBroadcast(initialUpdateIntent);

But for some reason the onUpdate function is not called! Does anyone know what the problem might be? Thanks.

2条回答
Luminary・发光体
2楼-- · 2020-07-13 08:22

Do you try to to catch your broastcast message in 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 */
    }
}

Otherwise, IMO it is better to define your own Message rather than using ACTION_APPWIDGET_UPDATE to clearly logic of update view of widget, something like that, in 1.Declare intent name in Manifest file:

<action android:name="com.yourdomain.youapp.SETTING_UPDATE" />

2.Define intent name:

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 */
    }
}

Hope it help ^^

查看更多
Lonely孤独者°
3楼-- · 2020-07-13 08:23

Try the following:

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);
}

Replace DayActivitiesAppWidget with your AppWidgetProvider class this way u update all your widget instances, then you can track down the issue with updating a single widget instance.

查看更多
登录 后发表回答