我有一个扩展 HandlerThread 并实现 Handler.Callback 的类。我无法理解如何设置处理程序以在此方案下相互发送消息。我的 Handler1 需要与 Handler2 对话,反之亦然,但因为这是在一个拥有自己的 looper 的 HandlerThread 中实现的,所以我不确定如何实例化这些对象。我只是坚持如何将其应用于语法。我已经在下面发布了我的破解。任何帮助表示赞赏。
...
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();
}
}