我有一个扩展HandlerThread并实现Handler.Callback的类。我无法理解如何设置处理程序在此方案下相互发送消息。我的Handler1需要与Handler2交谈,反之亦然,但因为这是在HandlerThread中实现的,它有自己的looper,我不知道如何实例化这些对象。我只是坚持如何将其应用于语法。我在下面发布了我的破解。任何帮助表示赞赏。
...
public class MyClass implements Runnable {
private Handler handler1 = null;
private Handler handler2 = null;
CyclicBarrier barrier = new CyclicBarrier(2);
class myThread extends HandlerThread implements Handler.Callback {
...
@Override
protected void onLooperPrepared() {
handler1 = new Handler(getLooper(), this){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
}
};
handler2 = new Handler(getLooper(), this){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
}
};
try {
barrier.await();
} catch (Exception e) {
e.printStackTrace();
}
Runnable runnable1 = new Runnable(){
@Override
public void run() {
Message message = Message.obtain();
message.setTarget(handler2);
message.obj = handler2;
message.sendToTarget();
}
};
Runnable runnable2 = new Runnable(){
@Override
public void run() {
Message message = Message.obtain();
message.obj = handler1;
message.setTarget(handler1);
}
};
}
@Override
public boolean handleMessage(Message reqMsg) {
//do some work
return true;
}
}
...
public void run() {
Thread mThread1 = new Thread(runnable1);
Thread mThread2 = new Thread(runnable2);
mThread1.start();
mThread2.start();
}
}
答案 0 :(得分:0)
以下是重构代码:
public class MyClass implements Runnable
{
private Handler handler1 = null;
private Handler handler2 = null;
CyclicBarrier barrier = new CyclicBarrier(2);
class myThread extends HandlerThread implements Handler.Callback
{
public myThread(String sName)
{
super(sName);
}
@Override
protected void onLooperPrepared() {
handler1 = new Handler(getLooper(), this){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
}
};
handler2 = new Handler(getLooper(), this){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
}
};
try {
barrier.await();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean handleMessage(Message reqMsg) {
//do some work
return true;
}
}
Runnable runnable1 = new Runnable(){
@Override
public void run() {
Message message = Message.obtain();
message.setTarget(handler2);
message.obj = handler2;
message.sendToTarget();
}
};
Runnable runnable2 = new Runnable(){
@Override
public void run() {
Message message = Message.obtain();
message.obj = handler1;
message.setTarget(handler1);
}
};
public void run() {
Thread mThread1 = new Thread(runnable1);
Thread mThread2 = new Thread(runnable2);
mThread1.start();
mThread2.start();
}
} }