从服务更新小部件

发布于 2024-12-06 22:37:40 字数 507 浏览 1 评论 0原文

我正在尝试从服务更新小部件...服务启动一个执行此代码的线程,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

饮湿 2024-12-13 22:37:40

你没有错。您只需更新小部件而不调用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 the ACTION_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 whole AppWidgetProvider is just a BroadcastReceiver that does some work for you already - and it does start the update in the same way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文