Kratz Kratz - 3 years ago 160
Android Question

Update Android Widget From Activity

I have a widget, its setup so that when I click on it, it opens some settings in an activity.

views.setOnClickPendingIntent(R.id.btnActivate, pendingIntent);


This configures some settings for the application. What I want to achieve is to have the widget update its view to reflect the changed settings when the Activity I launch closes. Using the update interval or any other type of polling isn't appropriate for this.

I've seen a couple places here and in the android docs this code used:

appWidgetManager.updateAppWidget(mAppWidgetId, views);


But I don't know how to get the mAppWidgetId value. I tried following the example for a widget configuration activity here http://developer.android.com/guide/topics/appwidgets/index.html, but in the following code,

Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
mAppWidgetId = extras.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
}


extras is always null, so I never get the AppWidgetID.

Ok, now I'm just rambling. What do you think I can do?

Answer Source

I finally found the answer I was looking for, it was in an overload of the updateAppWidget function.

   appWidgetManager.updateAppWidget(new ComponentName(this.getPackageName(), Widget.class.getName()), views);

This let me access the widget without having to know the appWidgetID. My final code in my activity is then:

        // Create an Intent to launch ExampleActivity
    Intent intent = new Intent(this, Settings.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

    views.setOnClickPendingIntent(R.id.btnActivate, pendingIntent);

    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
    appWidgetManager.updateAppWidget(new ComponentName(this.getPackageName(), Widget.class.getName()), views);
    finish();

I have to do all the same setup stuff I had to do in the onUpdate method of the Widget, but now every time I exit my activity the Widget is displaying the correct state.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download