Android Handlers - inter-thread communication
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?
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
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?
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
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
精彩评论