以编程方式更新活动/服务/接收器的小部件

我知道这是可能的,但我无法find一种方法来触发从主要活动更新我的部件。 是不是有一些我可以播放的一般意图?

Solutions Collecting From Web of "以编程方式更新活动/服务/接收器的小部件"

如果您正在使用AppWidgetProvider ,则可以通过以下方式进行更新:

 Intent intent = new Intent(this, MyAppWidgetProvider.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: int[] ids = AppWidgetManager.getInstance(getApplication()) .getAppWidgetI‌​ds(new ComponentName(getApplication(), MyAppWidgetProvider.class)); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids); sendBroadcast(intent); 

这有助于我search如何从服务/或操作更新小部件 (但可能从每个上下文):

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

所以要从一个活动更新一个小部件,你可以这样做:

 Intent intent = new Intent(this, DppWidget.class); intent.setAction("android.appwidget.action.APPWIDGET_UPDATE"); int ids[] = AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), DppWidget.class)); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,ids); sendBroadcast(intent); 

适用于我:)

尝试这个:

 int[] ids = AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), MyWidget.class)); MyWidget myWidget = new MyWidget(); myWidget.onUpdate(this, AppWidgetManager.getInstance(this),ids); 
 int widgetIDs[] = AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), WidgetProvider.class)); for (int id : widgetIDs) AppWidgetManager.getInstance(getApplication()).notifyAppWidgetViewDataChanged(id, R.id.widget_view); } 

如果您正在使用ListView,GridView或StackView等集合的小部件来更新小部件的项目,请执行以下操作:

 Context context = getApplicationContext(); AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); ComponentName thisWidget = new ComponentName(context, StackWidgetProvider.class); int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget); appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.stack_view); 

通过这个方法notifyAppWidgetViewDataChanged(),你可以强制widget项目实时获取任何新的数据。

只需获取一个AppWidgetManager实例并直接更新即可。 或者,如果您正在使用IntentService执行更新,请在IntentService上调用startService()AppWidgetProvider一种更新应用程序小部件的方式,但它不是唯一的方法。