Handler构造函数,创建实例
概述
Handler的构造分为两类,一类是在UI线程创建实例,一类在非UI线程创建实例。区别是Looper的获得方式。
使用构造方法创建实例
在UI线程创建实例
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
return false;
}
});
在非UI线程创建实例
class LooperThread extends Thread{
@Override
public void run() {
//1.初始化Looper
Looper.prepare();
//2.创建Handler实例
new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
return false;
}
});
//3.Looper循环
Looper.loop();
}
}
源码分析
- 在UI线程创建实例j
public Handler() {
this(null, false);
}
public Handler(Callback callback) {
this(callback, false);
}
public Handler(boolean async) {
this(null, async);
}
public Handler(Callback callback, boolean async) {
......
}
1.Callback:方法回调,将Message传回UI线程
public interface Callback {
/**
* @param msg A {@link android.os.Message Message} object
* @return True if no further handling is desired
*/
public boolean handleMessage(Message msg);
}
2.async:true为异步,false为同步
//当async为true时
msg.setAsynchronous(true);
3.下文是上面所有构造方法中展示的最后一个的全文
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
//关联Looper,已在UI线程中创建了Looper
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
//获得消息栈
mQueue = mLooper.mQueue;
//传入CallBack,async参数
mCallback = callback;
mAsynchronous = async;
}
- 在非UI线程创建实例
public Handler(Looper looper) {
this(looper, null, false);
}
public Handler(Looper looper, Callback callback) {
this(looper, callback, false);
}
public Handler(Looper looper, Callback callback, boolean async) {
//传入looper,callback,async参数
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
总结
1.UI线程已经初始化Looper,所以不需要再次初始化,而其他线程并没有初始化,所以需要初始化。