I am confused on the function of Looper
in the Handler
.
I have some code like this:
snippet1:
mThread = new Thread(){
@Override
public void run() {
Log.d(tag, "thread 1 current thread:" + Thread.currentThread());
//if(null == Looper.myLooper()) {// This is redundant.
//Looper.prepare();
//}
Log.d(tag, "thread 2 current thread:" + Thread.currentThread());
mHandler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
Log.d(tag, "thread 3 current thread:" + Thread.currentThread());
}
};
mHandler.sendEmptyMessage(0);
//Looper.loop(); // This is redundant since mHandler has a mainLooper, and loop in main thread.
}
};
snippet2:
mThread = new Thread(){
@Override
public void run() {
Log.d(tag, "thread 1 current thread:" + Thread.currentThread());
if(null == Looper.myLooper()) {
Looper.prepare();
}
Log.d(tag, "thread 2 current thread:" + Thread.currentThread());
mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
Log.d(tag, "thread 3 current thread:" + Thread.currentThread());
}
};
mHandler.sendEmptyMessage(0);
Looper.loop();
}
};
With different Looper
passed to the Handler, I got different output from handleMessage
, the snippet1 log "thread 3" output main thread, the snippet2 log "thread 3" output child thread, so I am confused on the function of Looper
passed to Handler
, can it switch the thread where to handle the method handlerMessage
. I haven't found any clue in the Handler
source.
Anyone can help me out, thanks in advance.