Update Android Widget From Activity

android widget update automatically
how to create widget in android programmatically
android add widget to home screen programmatically
android widget tutorial
android widget size
android widget tutorial android studio
android widget resize programmatically
android:updateperiodmillis

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?

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.

Update Android Widget From Activity, Code a Widget for Your Android App: Updating the Widget user experience, and how to enhance your widget with a configuration Activity. To add your widget, press any empty space on the homescreen, tap Widget and then select your widget. You'll get a chance to resize and reposition the widget, as necessary. The Last Update value will display the time that you created this widget. Press Tap to Update and the widget should display a toast and a new time.

There's another way to do it - pass the widget id in the pending intent that you use to start the activity:

Intent clickIntent=new Intent(context, MyConfigActivity.class);
clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
// you have the widgetId here, since it's your onUpdate
PendingIntent pendingIntent=PendingIntent
        .getActivity(context, 0,
                clickIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.btnActivate, pendingIntent);

Moreover, to avoid duplication of code from onUpdate(), you can broadcast an intent back to the AppWidgetProvider:

Intent intent = new Intent(this,MyAppWidgetProvider.class);
intent.setAction("android.appwidget.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:
int[] ids = {widgetId};
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,ids);
sendBroadcast(intent);

Build an App Widget, Exercise: widget with fixed update interval This article describes how to create home screen widgets in Android. Optional you can specify a configuration activity which is called once a new instance of the widget is added  For developing configuration feature, configuration activity and UI which allows user to configure widget needs to be created in the app. Widget configuration option can be shown when an instance of widget is created or every time a widget is clicked.

I know this has been answered and accepted way ago. However while I was searching the same thing I came across an awesomely simple way to update the widget.

For future readers:

The best part, this works for all the instances of the widget and from any context (Activity, Service etc)

Heres the code,

Context context = this;
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_2x1);
ComponentName thisWidget = new ComponentName(context, MyWidget.class);
remoteViews.setTextViewText(R.id.my_text_view, "myText" + System.currentTimeMillis());
appWidgetManager.updateAppWidget(thisWidget, remoteViews);

Courtesy - Stuck :)

Code a Widget for Your Android App: Updating the Widget, Additionally, you can implement an App Widget configuration Activity. how often to update the App Widget, and (optionally) a configuration Activity to launch at  Any call to updateWidgets () will cause all instances of our widget to be updated. Clicking the widget will cause all instances of our widget to be updated. NO SERVICE REQUIRED. Of course, be careful not to update to often - widget updates use battery power.

Instead of doing the call from your activity, I prefere to send a broad cast request to the widget for updating. The onUpdate method will be triggered and all widget layouts are passed.

Here is my code below:

1- sending broad cast from the activity:

Intent intent = new Intent(ctxt, MyAppWidgetProvider.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);

int[] ids = {R.layout.appwidget};
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,ids);
ctxt.sendBroadcast(intent);

and now, 2- implement the onUpdate method:

Intent i = new Intent(ctxt, Settings.class);
PendingIntent pi = PendingIntent.getActivity(ctxt, 0, i, 0);

for (int widgetId : allWidgetIds) {
    RemoteViews remoteViews = new RemoteViews(ctxt.getPackageName(), widgetId);
    remoteViews.setTextViewText(R.id.statusMsg, msg);
    remoteViews.setOnClickPendingIntent(R.id.rootView, pi);
    AppWidgetManager mngr = AppWidgetManager.getInstance(ctxt);
    ComponentName wdgt = new ComponentName(ctxt, MyAppWidgetProvider.class);
    mngr.updateAppWidget(wdgt, remoteViews);
}

That is it! I wish it helps you :)

Android (Home screen) Widgets - Tutorial, Understanding the logic and depth diving into Android Widgets with 4 sample Programmatically update widget from activity or service  After you have the string, update the widget. In updateAppWidget() add this before the last call: views.setTextViewText(R.id.coffee_quote, getRandomQuote(context)) That’s it. Every time the widget updates, you get a new quote! Making it personal. People like to personalize the look and functionality of their Home screens, and Widgets are no exception.

RemoteViews view = new RemoteViews("pakagename", R.layout.widget_layout_name);
view.setTextViewText(R.id.textView_id, String.valueOf(hr + ":" + mi)); // for setting a textview
view.setCharSequence(R.id.PunchIn, "setText", "Punch In"); //for setting a button name
view.setInt(R.id.PunchIn, "setBackgroundResource", R.color.black); //for setting button color
ComponentName theWidget = new ComponentName(getActivity(), AppWidget_name.class);
AppWidgetManager manager = AppWidgetManager.getInstance(getActivity());
manager.updateAppWidget(theWidget, view);

Android - App Widgets, java is added to your project. The Android manifest is updated to include the provider and configuration activity classes. Updating the widget provider-info file. The  Android triggers the configure activity that belongs to your widget and awaits result data. If the user did not configure as we expected, let’s say she pressed back button without entering a

Android Widgets - Android Bits, It is the responsibility of the configuration Activity to perform the first update when​  When an App Widget uses a configuration Activity, it is the responsibility of the Activity to update the App Widget when configuration is complete. You can do so by requesting an update directly from the AppWidgetManager. Here's a summary of the procedure to properly update the App Widget and close the configuration Activity:

2.1: App widgets · GitBook, The fact that, most of widgets that you can see on your device are auto-update information, for example: weather widget, location widget,. // Retrieve the widget’s layout// RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.activity_main); // Tell the AppWidgetManager to perform an update on this application

App Widgets, The biggest change to the foundations of Android to date: a modular architecture that makes it easier and faster for hardware makers to deliver Android updates. TextView autosizing Developers can now let the size of their text expand or contract automatically based on the size and characteristics of the TextView, making it much easier to

Comments
  • Thanks for sharing the answer!!! Where do we have to put this code, inside widget setting activity or inside widget class???
  • Nevermind, i put this inside updateWidget method, changed some "this" by "context" and removed ' AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this)' Now it is working... thanks!
  • If you have multiple configurations for the widgets, you might want to try appWidgetManager.getAppWidgetIds(component) and then iterate over them.
  • @Kratz I am facing the same issue but not able to figure it out where to write this in my code stackoverflow.com/questions/15523736/…
  • it is so frustrating that this does not respect the DRY principle, there has to be a way
  • Thanks for sharing code. Now i can able to update widget from the activity
  • This!! I've been battling for ages with trying to get a TextView on a widget updated, and this solved it. Thank you!! :)
  • Your most welcome. Pleasure is mine. Happy Coding. :)