简体   繁体   English

将数据从UI线程发送到主活动“ Android”未在其中创建的另一个线程

[英]send data from the UI thread to another thread which is not created in by the Main Activity “Android”

I checked in several websites but i didn't find an answer to this question. 我检查了几个网站,但没有找到这个问题的答案。

I have a UI thread that calls a service with an alarmManager at a specific frequency. 我有一个UI线程,该线程以特定频率调用带有alarmManager的服务。 and the service by itself calls another IntentService, that starts a Server/client thread. 并且该服务本身调用另一个IntentService,后者启动服务器/客户端线程。 I want to know if it is possible to make the Server/Client Threads communicate with the UI thread? 我想知道是否可以使服务器/客户端线程与UI线程通信?

Thanks a lot for your help. 非常感谢你的帮助。

The IntentService.onCreate() method is always executed on the UI thread. IntentService.onCreate()方法始终在UI线程上执行。 You can create a new Handler instance inside that method and store it in an instance or a class data member of your IntentService implementation. 您可以在该方法内创建一个新的Handler实例,并将其存储在IntentService实现的实例或类数据成员中。 You can use this Handler to post(Runnable) to be executed on the UI thread, or sendMessage(Message) which will be processed on the UI thread by your handleMessage(Message) implementation. 您可以使用此Handler程序post(Runnable)在UI线程上执行的sendMessage(Message) ,也可以使用sendMessage(Message)进行发布,该handleMessage(Message)将由handleMessage(Message)实现在UI线程上进行处理。 I would suggest to stick with post(Runnable) for simplicity. 为了简单起见,我建议坚持使用post(Runnable)

Update based on your comment: 根据您的评论进行更新:

Assuming your background thread does continuous processing on its own and does not have a looper, the easiest way would be to create a queue ( ArrayList<MyLocation> would work for example), and add each new location to the tail of it from the UI thread. 假设您的后台线程自己进行连续处理并且没有ArrayList<MyLocation> ,最简单的方法是创建一个队列(例如ArrayList<MyLocation>可以工作),然后从UI将每个新位置添加到它的尾部线。 Meanwhile the background thread picks the next location from the head and processes it as expected. 同时,后台线程从头部拾取下一个位置并按预期进行处理。 This is a very simple asynchronous way of communicating between the two threads (and is essentially a simplified version of how Looper and Message work). 这是在两个线程之间进行通信的一种非常简单的异步方式(本质上是LooperMessage工作方式的简化版本)。

However, the main drawback of this approach is that your background thread is always busy thus waisting CPU resources if there are no incoming location updates. 但是,此方法的主要缺点是您的后台线程始终很忙,因此如果没有传入的位置更新,则会占用CPU资源。 The better alternative would be to change your background thread to be a Looper thread and send Message to it. 更好的选择是将您的后台线程更改为Looper线程并向其发送消息。 Here's an example of how to Create Looper thread and send a Message to it . 这是一个如何创建Looper线程并向其发送消息的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM