简体   繁体   中英

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. and the service by itself calls another IntentService, that starts a Server/client thread. I want to know if it is possible to make the Server/Client Threads communicate with the UI thread?

Thanks a lot for your help.

The IntentService.onCreate() method is always executed on the UI thread. 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. 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. I would suggest to stick with post(Runnable) for simplicity.

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. 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).

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. The better alternative would be to change your background thread to be a Looper thread and send Message to it. Here's an example of how to Create Looper thread and send a Message to it .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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