将更新的数据发送到后台线程
我有一个后台线程,它将有关应用程序当前状态的数据发送到服务器。线程应该不断地(或者至少在状态发生变化时)发送此数据。
数据来自 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的后台工作人员不能每隔几毫秒检查一次线程安全的数据结构吗?主线程只是填充它,后台工作人员用它来做它想做的事。
或者只使用由信号量包围的静态变量。丑陋但它会起作用。
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.