从服务更新小部件
我正在尝试从服务更新小部件...服务启动一个执行此代码的线程,
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(Worker.this);
RemoteViews remoteViews = new RemoteViews(Worker.this.getPackageName(), R.layout.mywidget);
ComponentName projectWidget = new ComponentName(Worker.this, MyWidget.class);
remoteViews.setTextViewText(R.id.widgetstate, "update");
appWidgetManager.updateAppWidget(projectWidget, remoteViews);
onUpdate 方法仅打印日志,但此日志仅在我创建小部件时打印,而不是每次线程循环时打印。我哪里错了?
提前致谢
I'm trying to update a widget from a service... the service start a thread that execute this code
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(Worker.this);
RemoteViews remoteViews = new RemoteViews(Worker.this.getPackageName(), R.layout.mywidget);
ComponentName projectWidget = new ComponentName(Worker.this, MyWidget.class);
remoteViews.setTextViewText(R.id.widgetstate, "update");
appWidgetManager.updateAppWidget(projectWidget, remoteViews);
the onUpdate method just print a log, but this log is printed only when I create the widget, not everytime the thread cycles... where I'm wrong?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你没有错。您只需更新小部件而不调用
onUpdate()
。它只是一个方便的方法,被调用以响应系统广播的ACTION_APPWIDGET_UPDATE
。您不必调用它来更新小部件,它也像您在这里所做的那样工作。 1要调用它,您可以发送广播或手动调用它,但从代码结构的角度来看,最好将小部件更新功能保留在一个地方,以便轻松查找内容。
1 看一下
AppWidgetProvider
源代码,第 56 行。整个AppWidgetProvider
只是一个BroadcastReceiver
,它已经为您完成了一些工作 - 并且它确实以相同的方式启动更新。You're not wrong. You just update the widget without calling
onUpdate()
. It's just a convinience method that gets called in response to theACTION_APPWIDGET_UPDATE
broadcast by the system. You don't have to call it to update a widget, it also just works like you did here. ¹To invoke it you can send the broadcast or call it by hand though, it's a good idea to keep the widget update functionality in one place from a code structure point of view to find things easily.
¹ Take a look at the
AppWidgetProvider
source, line 56. The wholeAppWidgetProvider
is just aBroadcastReceiver
that does some work for you already - and it does start the update in the same way.