Reputation: 609
I am programming in Android environment, and I have in my project a Main Activity, in which there is an AsynkTask class, and separately a Thread object, realized extending Runnable interface. Now, AsynkTask and the Thread can be seen as two worker threads managed by the main thread, that is the Main Activity. How can I do if I want to make possible the communication between the two worker threads, not involving the main thread? How can I use handlers to realize this? I know how to use handlers between main and worker threads. I want to know how use them only between the worker threads, because in this case I can't pass in constructors handlers, because in this case I can not directly instantiate a thread, passing it as a parameter the handler created by the main thread. The main thread must create two worker threads, and they must communicate without the involvement of the main thread. I hope I have been clear enough.
Upvotes: 3
Views: 2524
Reputation: 48262
If you want to use a Handler with a worker thread you have to create a Looper on that Thread as explained in http://developer.android.com/reference/android/os/Looper.html.
Like this:
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
And then you can send messages to mHandler
from any other Thread
.
Upvotes: 2