Handler机制的作用
- 用于线程间通讯 (进程可以包含一到多个线程,进程和线程的本质区别是能否共享资源,Android进程隔离)
- 子线程UI操作都是通过Handler实现 (Android UI单线程模型,只能在UI线程更新UI)
Handler消息机制模型
Message:消息的载体,分为硬件产生的消息(如按钮、触摸)和软件生成的消息;(what / arg1 / arg2 / obj)
MessageQueue:消息队列,单链表维护Message,主要功能向消息池投递消息(MessageQueue.enqueueMessage)和从消息池取走消息(MessageQueue.next);
Handler:消息辅助类,主要功能向消息池发送各种消息事件(Handler.sendMessage)和处理相应消息事件(Handler.handleMessage);
Looper:创建Looper和MessageQueue,执行Looper.loop,遍历取出消息,分发给Handler进行处理。
Handler使用:
通匿名内部类的方式创建Hanlder,可能会存在内存泄露的问题。
handler.sendMessage发出的msg持有handler的引用,消息经过looper分发回到handler.handleMessage时,这个时候activity可能已经finish掉了,但是由于handler持有Activity的引用,导致activity应当被系统回收的时候却没有被回收,发生了内存泄露。主线程Looper的生命周期是伴随整个应用程序的。
内存泄露总的来说是因为长存对象拥有对短存对象的引用,导致短存对象被销毁时没办法及时被GC回收。
-
写一个静态内部类StaticHandler,并通过弱引用的方式持有DownLoadActivity的引用,接收Message,更新UI。
-
点击按钮,创建线程,模拟下载过程,通过定义的handler发送Message。
-
Message可以直接new Meesage()或者Message.Obtain()(推荐Obtain,为啥稍后解释),并让Message携带消息。
这个例子里还是存在内存泄露,是由new Thread(new Runnable() {}).start()导致的,因为activity finish之后,Thread只要任务没有结束,就会一直运行下去,而这个thread仍然持有activity的引用,activity无法被回收。我就懒得写了。
public class DownloadActivity extends AppCompatActivity {
private StaticHandler handler = new StaticHandler(this);
private Button downloadBtn;
private TextView displayTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handler_test);
downloadBtn = findViewById(R.id.downloadBtn);
displayTv = findViewById(R.id.displayTv);
downloadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
Log.e("zhen", "thread: " + Thread.currentThread().toString());
try {
int i = 0;
do{
Thread.sleep(2000);
i += 20;
Message msg = Message.obtain();
msg.arg1 = i;
handler.sendMessage(msg);
} while(i < 100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
});
}
public void updateProgress(int msg) {
displayTv.setText("更新进度..." + msg + "%");
Log.e("zhen", "更新进度..." + msg + "%");
}
static class StaticHandler extends Handler{
private WeakReference<DownloadActivity> mWeakReference;
public StaticHandler(DownloadActivity activity) {
mWeakReference = new WeakReference<DownloadActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
final DownloadActivity activity = mWeakReference.get();
if (activity != null) {
activity.updateProgress(msg.arg1);
}
}
}
}
复制代码
日志打印:每次点击都重新创建线程(至于线程复用、线程池的问题我们下下一篇文章再讨论)
UI展示同日志一样
源码进阶
从例子里看出,我们创建了Message,创建了Handler,并在子线程里通过Handler.sendMessage()发送出消息;在Handler.handleMessage()对Message进行处理,更新UI。但是它是怎么切换线程的呢?Looper和MessageQueue在哪里创建的呢?哪里进行MessageQueue.enqueueMessage()、MessageQueue.next()?哪里进行Looper.prepare()、Looper.loop()?
首先跟大家说下,如果要创建子线程的Handler,需要手动写Looper.prepare()、Looper.loop(),下一节我们分析HandlerThread就明白了。但是主线程系统已经为我们创建好了mainLooper,这节我们先来分析系统为我们创建好的looper。
ActivityThread的应用程序的主入口,系统打开应用时会首先调用ActivityThread.main(),Looper的创建和循环都是在里面操作的,下面我们来看下源码。
ActivityThread.java # main()
public static void main(String[] args) {
Looper.prepareMainLooper(); //创建Looper和MessageQueue
ActivityThread thread = new ActivityThread();
thread.attach(false); //会执行Application.onCreate()
Looper.loop(); //while(true) 死循环
throw new RuntimeException("Main thread loop unexpectedly exited");
}
复制代码
prepareMainLooper()
-
Looper.prepare() 会创建Looper对象,Looper对象实例化时会创建MessageQueue,每个线程只能执行一次,
-
prepare(true) 表示允许这个Looper运行时退出,对于false表示当前Looper运行时不允许退出。
-
线程本地存储区(Thread Local Storage,简称为TLS),每个线程都有自己的私有的本地存储区域,不同线程之间彼此不能访问对方的TLS区域
/**
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
//每个线程只能执行一次,quitAllowed为true表示允许Looper运行时退出,false表示不允许运行时退出
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)); //给每个线程配置一个Looper对象
}
//Looper对象实例化时会创建MessageQueue
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
复制代码
loop()
线程是一段可执行的代码,当可执行代码执行完成后,线程生命周期便会终止,线程就会退出,那么做为App的主线程,如果代码段执行完了会怎样?,那么就会出现App启动后执行一段代码后就自动退出了,这是很不合理的。所以为了防止代码段被执行完,只能在代码中插入一个死循环,那么代码就不会被执行完,然后自动退出。
循环遍历,从MessageQueue中取出Message,传递给Handler进行处理(消息分发)。
public static void loop() {
final Looper me = myLooper(); //通过ThreadLocal得到当前线程的looper对象
if (me == null) { //主线程会帮我们创建好looper对象,子线程需要手动调用Looper.prepare()来创建
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue; //Looper对象会持有MessageQueue的引用
for (;;) {
Message msg = queue.next(); // might block 取出一个Message
if (msg == null) { //MessageQueue为空,没有消息
// No message indicates that the message queue is quitting.
return;
}
msg.target.dispatchMessage(msg);
msg.recycleUnchecked();
}
}
复制代码
disptatchMessage()
msg.target:target是一个Handler对象,所以会来到Handler.java # dispatchMessage(),进行消息处理
dispatchMessage()会有一个优先级分发问题:
1、如果msg.callback不为空,执行msg.callback.run()方法
2、如果mCallback接口不为空,执行mCallback.handleMessage()
3、如果都为空,执行Handler内置的handleMessage,一般子类会重写这个方法
public void dispatchMessage(Message msg) {
if (msg.callback != null) { //msg.callback是个Runnable对象
handleCallback(msg); //如果msg.callback不为空,执行msg.callback.run()方法
} else {
if (mCallback != null) { //如果接口不为空,执行mCallback.handleMessage方法
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
//如果msg.callback不为空,执行runnable方法
private static void handleCallback(Message message) {
message.callback.run();
}
//如果接口不为空,执行接口的handleMessage方法
final Callback mCallback;
public interface Callback {
public boolean handleMessage(Message msg);
}
//Handler内置的handleMessage,我们一般会重写这个方法,来处理消息。
public void handleMessage(Message msg) {
}
复制代码
前面我们讲了怎么创建Looper/MessageQueue对象,并且进行消息分发和回调处理。那么消息是怎么进入到MessageQueue中的呢? 这里就涉及到了前面的handler.sendMessage(),首先我们得创建一个Message对象
Message的创建
我们可以直接new Message() 或者Message.obtain()来得到一个消息对象。
Message.obtain() 会进行Message的复用,更省资源,这也就是我们为什么推荐用Message.obtain()来获取消息
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
复制代码
sendMessage()
public final boolean sendMessage(Message msg) {
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue; //必须要有MessageQueue
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this; //message持有handler的引用
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
复制代码
enqueueMessage
MessageQueue队列,先进先出,这里采用单链表的形式实现。插入链表的尾部,则必然从链表的头部取出数据。
boolean enqueueMessage(Message msg, long when) {
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) { //空链表,直接赋值
msg.next = p;
mMessages = msg;
} else {
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
}
msg.next = p;
prev.next = msg;// 插入链表的尾部
}
}
return true;
}
复制代码
上面我们解释了handler.sendMessage() 是怎么放入MessageQueue中去的,并且message必须要配置target对象。那么MessageQueue是从哪里来的呢?
Handler实例化
没有指定Looper,则取当前线程的Looper对象;如果指定了不同线程的Looper对象,则创建该线程下的Handler对象;callback默认为null, async默认为false。
Handler持有Looper和MessageQueue对象的引用,每个Looper对象对应一个MessageQueue对象。
public Handler() { this(null, false); }
public Handler(Callback callback) { this(callback, false); }
public Handler(Looper looper) { this(looper, null, false); }
public Handler(Looper looper, Callback callback) { this(looper, callback, false); }
public Handler(boolean async) { this(null, async); }
public Handler(Callback callback, boolean async) {
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
复制代码
现在应该是把所有流程都说完了。
**Handler机制总结:
- 每个线程有且只有一个Looper对象,一个Looper对应一个MessageQueue消息队列,单链表维护Message。
- 主线程的Looper对象在应用程序的主入口出,系统已通过prepareMainLooper()创建好了
- Looper.loop中通过MessageQueue.next取出Message,进行分发;如果没有Message,则进入nativePollOnce,释放资源,等待唤醒。
- handler.sendMessage发送消息,messageQueue.enqueueMessage放入链表尾部
- handler.handleMessage处理消息,是looper.loop里msg.target.dispatchMessage进行分发
ActivityThread是App的入口,main里做了死循环的操作,为啥没有卡死呢?
主线程的死循环一直运行是不是特别消耗CPU资源呢? 其实不然,这里就涉及到Linux pipe/epoll机制,简单说就是在主线程的MessageQueue没有消息时,便阻塞在loop的queue.next()中的nativePollOnce()方法里,此时主线程会释放CPU资源进入休眠状态,直到下个消息到达或者有事务发生,通过往pipe管道写端写入数据来唤醒主线程工作。这里采用的epoll机制,是一种IO多路复用机制,可以同时监控多个描述符,当某个描述符就绪(读或写就绪),则立刻通知相应程序进行读或写操作,本质同步I/O,即读写是阻塞的。 所以说,主线程大多数时候都是处于休眠状态,并不会消耗大量CPU资源。