Somewhere here on Stack Overflow, I had found the following code some day which I adjusted to my application a bit:
private void updateWidget() {
AppWidgetManager widgetManager = AppWidgetManager.getInstance(ctx);
ComponentName widgetComponent = new ComponentName(ctx, MyAppWidgetProvider.class);
int[] widgetIds = widgetManager.getAppWidgetIds(widgetComponent);
Intent update = new Intent();
update.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, widgetIds);
update.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
ctx.sendBroadcast(update);
}
This should programmatically refresh all instances of the application’s widget. ctx is the Activity‘s context (this) that I set once in onCreate(). The method above is called in the Activity‘s onStop() method.
Unfortunately, when it is called, it replaces the app’s widget by other apps’ widgets (e.g. AP News) – at least for a while.
How can this happen? Is there something wrong in the code?
Thank you!
Edit #1: To point this out more clearly: I’ve already defined an interval for automatic refreshing. But in addition to that, I would like to update the widget from the Activity from time to time. This question suggests that it is possible as well.
Edit #2: I’ve just seen that the wrong widget is only shown for some seconds. After that, my own app’s widget is shown again.
I had some problems with widgets in the past, and have solved them. I really do not know the reason why my solution worked for me. And as it worked for Marco W., so I place it here: all I did was moved the update code to a service. When I need to update, start that service. Again, I’m not sure about that but the problems were solved.
Thanks Marco, I got some more experiences with Android. It’s funny 🙂