我的应用程序类中有此处理程序类:
private static class MyHandler extends Handler{
private final WeakReference<MyApplication> weakReference;
MyHandler(MyApplication myApplication){
super(Looper.getMainLooper());
weakReference = new WeakReference< MyApplication >(myApplication);
}
@Override
public void handleMessage(Message msg) {
Log.d(ApplicationConstants.TAG,"Inside handling message of handler");
MyApplication myApplication = weakReference.get();
if(myApplication!=null){
//do some work
}
}
}
它是在onCreate()
myHandler = new MyHandler(this);
waiter = new Waiter();
waiter.start();
现在,在另一个Thread的run方法中,我正在使用Main Looper将消息发送到Main UI消息队列。
public class Waiter extends Thread {
@Override
public void run() {
//other business requirement codes including looping the thread, sleep and some computation
if(someCondition){
Handler handler = new Handler(Looper.getMainLooper());
Message message = Message.obtain(handler);
message.arg1=404;
handler.sendMessage(message);
//code to finish this thread
}
}
}
问题是handleMessage
没有被呼叫。
但是,如果我在服务程序线程中传递了对处理程序的引用,并使用该引用来调用sendMessage
函数,那么它将起作用。
像这样:
myHandler = new MyHandler(this);
waiter = new Waiter(myHandler);
waiter.start();
我的问题是为什么以前的方法不起作用?据我了解,由于正在使用主循环程序,因此处理程序仅在使用主消息队列。