Android Handlers - inter-thread communication

穿精又带淫゛_ 提交于 2019-12-09 07:51:28

问题


How do you implement two-way communication between two threads with Handlers in Android?

I have a Service A that spawns thread B. It's fairly easy to communicate from B to A, it's just to pass a Handler to the constructor of B, but how to do it from A to B? B does not have any Looper assigned to it automatically.

Has anyone got the answer?


回答1:


Here is good post explaining threads and communication using handlers. Also, the same blog has a number of posts regarding various thread constructs in Android




回答2:


To overcome the problem of getting a Handler for the Thread you just created (but which may not have initialized yet), see How to create a Looper thread, then send it a message immediately?




回答3:


Call Looper.prepare() in the new thread, and Looper will be created for you for that thread. Then you can create a Handler to pass back to the other thread.

That is, after calling Looper.prepare(), the statement Handler h = new Handler() will create a Handler on the Looper of your new thread.

http://developer.android.com/reference/android/os/Looper.html




回答4:


You Can Follow the Below Steps to implement two-way communication.

1) Create a worker thread which extends Thread Class .
2) Initialize a Handler with this worker Thread .
3) In its run() method prepare the looper for this thread by : Looper.prepare() for binding message queue to this thread and Looper.loop() to create a loop which will read the message and runnables from the Message Queue of this thread.

4) Send Messgae and Runnables from the UI Thread handler to this worker thread handler using the post() for runnables & sendMessage() for Messages .

Please refer this tutorial : Handle background work using Looper



来源:https://stackoverflow.com/questions/5657968/android-handlers-inter-thread-communication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!