我对Looper
中Handler
的功能感到困惑。
我有一些像这样的代码:
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();
}
};
将不同的Looper
传递给Handler,我从handleMessage
获得了不同的输出, snippet1 log" 3"输出主线程,snippet2 log"线程3"输出子线程,所以我对Looper
传递给Handler
的函数感到困惑,可以切换线程在哪里处理方法handlerMessage
。我还没有找到Handler
来源的任何线索。
任何人都可以帮助我,提前谢谢。