Home » Android » android appwidget won't update from activity

android appwidget won't update from activity

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a simple appwidget and I want to update it when an action occurs in an activity (in the same app). in onUpdate(), I immediately update the widget, which works fine. In my activity, I call the same static update method in my appwidget that is called in onUpdate() to update the views. the widget is not updated.

I can trace the code right into the AppWidgetManager.updateAppWidget() method, and all this good, but the widget does not update.

The only possible difference I can see is that the context object passed into my static update method is different, when it’s called from the context of an activity vs. the context of a appwidget’s onUpdate() method. however, there are lots of examples on the web of this so I expect it should work.

How to&Answers:

Without seeing your code I’m not 100% sure how you are trying to do it, however here is the method I use. Within my Activity I have the following method:

private void updateAllWidgets(){
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext());
    int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(this, MyWidget.class));
    if (appWidgetIds.length > 0) {
        new MyWidget().onUpdate(this, appWidgetManager, appWidgetIds);
    }
}

Where MyWidget is the class of the appwidget. I can call this method from anywhere within my Activity to update all my appwidgets.

Answer:

Rather than use a static method take advantage of the fact that the widget is already a broadcast receiver and register an update intent for it in your manifest. Then whenever you need to update it from the activity just call

//in your activity
sendBroadcast(new Intent(MyWidget.ACTION_UPDATE).putExtra(whatever));  



//In widget class
public static final String ACTION_UPDATE = "com.example.UPDATE_MY_WIDGET";

and inside the receiver tags of your manifest file

<intent-filter>
  <action android:name="com.example.UPDATE_MY_WIDGET"/>
</intent-filter>