将更新的数据发送到后台线程

发布于 2024-09-28 09:11:58 字数 310 浏览 3 评论 0原文

我有一个后台线程,它将有关应用程序当前状态的数据发送到服务器。线程应该不断地(或者至少在状态发生变化时)发送此数据。

数据来自 UI,用户可以随时更改状态(通过在屏幕上移动手指),因此我需要告诉后台线程发送更新的数据。

Android 有没有办法做到这一点?我的解决方案是保持线程的实例可用,并添加一些方法以允许设置要发送的线程的内部数据。但是我什至不确定这是否有效(假设该线程不在更新它的命令所在的主线程上运行)。我之前看过 AsyncTask,因为这似乎是后台工作人员的标准解决方案,但我没有看到任何可以将数据推送到该任务的东西(它只将数据/进度报告回 UI 线程)。

I have a background thread that is sending data about the application's current status to a server. The thread is supposed to constantly - or at least whenever the status changes - send this data.

The data is coming from the UI and the user is able to change the status any moment (by moving with the finger over the screen), so I need to tell the background thread to send the updated data.

Is there any Android way to do this? My solution would be to keep the thread's instance available and add some method to allow setting the thread's internal data that is to be send. However I'm not even sure if that even works (given that the thread doesn't run on the main thread where the command to update it would come from). I looked at AsyncTask before, as that seems to be the standard solution for background workers, but I didn't see anything that makes it possible to push data into that task (it only reports data/progress back to the UI thread).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

听不够的曲调 2024-10-05 09:11:58

你的后台工作人员不能每隔几毫秒检查一次线程安全的数据结构吗?主线程只是填充它,后台工作人员用它来做它想做的事。

或者只使用由信号量包围的静态变量。丑陋但它会起作用。

Can't your background worker check a thread-safe data structure every few milliseconds? The main thread just populates this and the background worker does what it wants with it.

Or just use a static variable surrounded by semaphores. Ugly but it would work.

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