测试代码
new Thread(new Runnable() {
@Override
public void run() {
/* Message message1 = Message.obtain();
message1.obj = "Handler源码分析";
mHandler.sendMessage(message1);
Message message2 = Message.obtain();
mHandler.sendMessageDelayed(message2, 1000);
Message message3 = Message.obtain();
mHandler.sendMessageDelayed(message3, 500);*/
Handler handler=new Handler();
}
}).start();
MessageQueue 消息队列
mHandler.sendMessage(message1)源码分析
public final boolean sendMessage(Message msg)
{
//默认设置消息延迟的时间是0
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
//这里为方便测试,我们默认系统时间不考虑,即message1默认delayMillis的时间是0
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
//默认消息队列肯定不是空的
MessageQueue queue = mQueue;
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) {
//注意这行将Hadler复制给msg.target
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
查看MessageQueue中的enqueueMessage的源码
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {//此时的msg.target等于Handler
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
msg.markInUse();
msg.when = when;//此时是message1,msg.when=0;
Message p = mMessages;//默认肯定是空
boolean needWake;
if (p == null || when == 0 || when < p.when) {
//message1进来
msg.next = p;//msg.next是为空
mMessages = msg;//mMessage=msg
needWake = mBlocked;
}
}
return true;
}
mHandler.sendMessageDelayed(message2, 1000);源码分析
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
//这里默认是1000
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
//其他和上面的message1源码分析走的流程一样直接看最后的MessageQueue中的enqueueMessage源码
boolean enqueueMessage(Message msg, long when) {
synchronized (this) {
msg.when = when;//1000
Message p = mMessages;//mMessage==Message1,所以P等于Message1
boolean needWake;
if (p == null || when == 0 || when < p.when) {//上一个message1等于0
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;//prev=messsage1
p = p.next;//此时p等于message指向的下一个指针即为空
if (p == null || when < p.when) {
break;//跳出
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
//message2下一个指针指向P即为空
msg.next = p;
//message1的下一个指针指向的是message2
prev.next = msg;
}
}
return true;
}
mHandler.sendMessageDelayed(message3, 500);源码分析
直接分析最后一步
boolean enqueueMessage(Message msg, long when) {
synchronized (this) {
msg.markInUse();
msg.when = when;//msg.when=500
Message p = mMessages;//还是message1
boolean needWake;
if (p == null || when == 0 || when < p.when) {
//还是不会走这儿
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;//message1
p = p.next;//message2
if (p == null || when < p.when) {//500<1000
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
//message3.next=message2
msg.next = p; // invariant: p == prev.next
//message1=message3
prev.next = msg;
}
}
return true;
}
handler.sendMessage只是将消息保存到消息队列中
Loop 消息循环
我们会知道在子线程中直接new Handler会出错
为什么会报错呢?我们看下源码
public Handler() {
this(null, false);
}
public Handler(Callback callback, boolean async) {
mLooper = Looper.myLooper();//获取一个looper
if (mLooper == null) {//looper为空的时候抛出异常,这也是为什么new Handler的时候会报错
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
//获得消息队列
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
mLooper源码分析
public static Looper myLooper() {
return sThreadLocal.get();
}
//static 也就是说一个线程中只有一个sThreadLocal
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
ThreadLocal.get源码分析
public T get() {
//获取当前线程
Thread currentThread = Thread.currentThread();
//此时默认是空的
Values values = values(currentThread);
if (values != null) {
Object[] table = values.table;
int index = hash & values.mask;
if (this.reference == table[index]) {
return (T) table[index + 1];
}
} else {
values = initializeValues(currentThread);
}
//此时默认是空的
return (T) values.getAfterMiss(this);
}
解决办法是
Looper.prepare();
Handler handler=new Handler();
Looper.loop();
Looper.loop源码分析
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//这里就解决了new Handler的时候为空
sThreadLocal.set(new Looper(quitAllowed));
}
//new Loope主要是new一个消息队列和获得当前线程
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
//设置set源码
public void set(T value) {
Thread currentThread = Thread.currentThread();
Values values = values(currentThread);
if (values == null) {
values = initializeValues(currentThread);
}
//key是ThreadLocal,因为它是唯一的所以值也是唯一的
values.put(this, value);
}
总结:其实就是创建一个 Looper ,并且保证一个 Thread 线程中,只有一个 Looper 对象
Looper.loop();源码分析
public static void loop() {
final Looper me = myLooper();//获得一个looper对象
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;//获得消息队列
final long ident = Binder.clearCallingIdentity();
for (;;) {//实际就是不断的获得下一个对象,直到消息队列中没有消息
Message msg = queue.next(); //指向下一个,链式表
if (msg == null) {
//如果消息为空返回
return;
}
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
//msg.target实际是Handler
msg.target.dispatchMessage(msg);
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
msg.recycleUnchecked();
}
}
Handler中的分发消息
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
//实际最终调用的是我们自己写的handlerMessage
public void handleMessage(Message msg) {
}
recycleUnchecked回收源码分析
void recycleUnchecked() {
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = -1;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {//最大是50
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
问题一:为什么主线程中不需要设置Looper.prepare
答:因为在我们应用启动的时候,ActivityThread 的入口函数 main() 方法中已经帮我们写了这行代码
Looper.prepareMainLooper();
Looper.loop();
问题二:为什么Mssage.obtain比new 一个Messae好
public static Message obtain() {//线程池没有就new有就拿
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();
}