Handler基本概念
Handler的主要用法
private Handler handlerSend = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
// 使用send方法更新UI的方式:
// 重写handleMessage方法,在该方法内更新UI
super.handleMessage(msg);
if (msg.what == 1) {
mTvTxt.setText("使用send方法更新UI");
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initBind();
mBtnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// 模拟send方法更新UI的操作
handlerSend.sendEmptyMessage(1);
}
});
thread.start();
}
});
}
再看Handler Post 一个Runnable的例子:
private Handler handlerPost = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initBind();
mBtnPost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 模拟post方法更新UI的操作
handlerPost.post(new Runnable() {
@Override
public void run() {
mTvTxt.setText("使用post方法更新UI");
}
});
}
});
}
这种实现方式的好处是,无需在Handler的创建位置重写handleMessage方法,直接在发送Runnable时在Runnable的run方法中实现消息的处理逻辑即可。因此,这种写法更为简洁,并且可以将发消息和消息处理逻辑写在一起,一定程度上提升了代码的可读性。
Handler实现原理
从设计模式上看, handler采用的是生产者-消费者模式, 子线程和主线程通过共享handler的内存,实现跨线程通信。
每个Handler都会关联一个消息队列,消息队列又是封装在Looper对象中,而每个Looper又会关联一个线程。这样Handler、消息队列、线程三者就关联上了。
//在handler构造函数中从looper中获取消息队列,与handler建立关联
public Handler(Callback callback, boolean async) {
//代码省略
mLooper = Looper.myLooper();//获取Looper
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;//通过Looper对象获取消息队列
mCallback = callback;
mAsynchronous = async;
}
//Looper中的prepare方法, 创建looper对象(含消息队列),并设置到关联线程上
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
我们将消息发送到消息队列,然后Handler通过对应的线程通过消息循环,从消息队列中逐个取出,并执行。
默认情况下,消息队列只有一个,也就是主线程的消息队列,该消息队列通过Looper.prepareMainLooper() 方法创建,最后执行Looper.loop()来启动消息循环。
Handler相关问题及答案
1. Handler线程安全如何实现的?
答:Handler的enqueMessage及next方法都加了sychronized同步锁
2. handler会持有外部对象,如何避免循环引用?
答:需要注意两个问题:
(1)将自定义handler声明为静态内部类或将handler中引用的外部对象声明为弱引用。
(2)退出activity时清空未执行的callback及消息