Android Handler机制详解
1. Handler基础
- Android规定只能在主线程更新UI,子线程需通过Handler发送消息至主线程处理,实现生产者-消费者模式。
- 系统源码中大量使用Handler,深入理解其原理对开发至关重要。
2. Handler基本使用
2.1 消息发送
所有消息最终调用enqueueMessage()方法入队:
private static final int MESSAGE_TEST_1 = 1;
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message msg) {
switch (msg.what) {
case MESSAGE_TEST_1:
tvTest.setText((String) msg.obj);
break;
}
return false;
}
});
常用发送方式:
sendMessage(Message):普通消息sendEmptyMessage(int):仅标记sendMessageDelayed(Message, long):延迟发送post(Runnable):直接执行任务
2.2 View.post()与runOnUiThread()
View的post()和Activity的runOnUiThread()均基于Handler实现:
tvTest.postDelayed(() -> tvTest.setText("5s"), 5000);
runOnUiThread(() -> updateUI());


