我相信我不理解Handler如何传递/接收消息。
我在另一个线程上创建了一个处理程序,然后让主线程向它发送一条消息。我是这样做的
public void startAniHandlerThread(int timer){
final int sleeptime = timer;
int test2;
Thread thread1 = new Thread(){
public void run(){
Looper.prepare();
Log.v("loop","looping");
Handler handler = new Handler(){
@Override
public void handleMessage(Message inputMessage) {
Log.v("Thread handler", "checking");
if(inputMessage.what == 10) {
if (inputMessage.arg1 == 2) {
Log.v("Thread handler", "stop");
} else if (inputMessage.arg1 == 1) {
Log.v("Thread handler", "continue");
} else{
Log.v("nothing", "nothing");
}
}
}
};
Looper.loop();
}
};
thread1.start();
}
以下是我尝试从UI线程向其发送消息的方式:
public void stopAniHandlerThread(){
Handler newHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
return false;
}
});
Runnable newRunable = new Runnable() {
@Override
public void run() {
Handler handler = new Handler();
Message message = new Message();
message.what = 10;
message.arg1 = 2;
handler.sendMessage(message);
}
};
newHandler.postDelayed(newRunable, 2000);
}
这是我得到的日志(我希望这个被调用,但它没有:
Log.v("Thread handler", "stop");
V / stopAniHandlerThread:发布 V /循环:循环