文章目录
  1. 1. 一、概述:
    1. 1.1. Android中太多的东西和Handler-Looper有关了(HandlerThread,IntentService),要想了解他们必须把Handler基础掌握,之前对Handler了解了不知道多少遍,今天终于看了一下源码。还好Handler,Looper,MessageQueue都没有很深的继承结构,代码量也不多,所以看起来比较轻松好理解。
  2. 2. 二、从基本的使用开始说起:
    1. 2.1. 1、首先new一个Handler调用构造函数:
      1. 2.1.1. 1.1在代码中我们看到初始化了mLooper变量和mQueue变量:
      2. 2.1.2. Looper.myLooper()是这样的:
      3. 2.1.3. 从装有Looper对象的ThreadLocal中取出一个Looper返回。那么取出来的是哪一个Looper那?我们看一下ThreadLocal的get()方法
    2. 2.2. 我们可以确定取出的是当前线程的Looper.
      1. 2.2.1. 通过上面这句我们知道MessageQueue是在Looper中的。
      2. 2.2.2. 在Looper的私有构造函数中初始化了一个MessageQueue对象。
    3. 2.3. Looper不断循环MessageQueue中的Message:
    4. 2.4. msg.target返回一个Handler对象。调用Handler的dispatchMessage()方法:
    5. 2.5. 在dispatchMessage方法中又回调了handleMessage(msg)方法
  3. 3. 结论:

一、概述:

Android中太多的东西和Handler-Looper有关了(HandlerThread,IntentService),要想了解他们必须把Handler基础掌握,之前对Handler了解了不知道多少遍,今天终于看了一下源码。还好Handler,Looper,MessageQueue都没有很深的继承结构,代码量也不多,所以看起来比较轻松好理解。

二、从基本的使用开始说起:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Handler mHandler = new Handler(){
@Override
public void handlerMessage(){
//
}
};


new Thread(new Runnable(){
public void run(){
mHandler.sendEmptyMessage(xxx);
}

}).start();

1、首先new一个Handler调用构造函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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());
}
}

mLooper = Looper.myLooper();//mLooper对象的初始化
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;//mQueue对象的初始化
mCallback = callback;
mAsynchronous = async;
}

1.1在代码中我们看到初始化了mLooper变量和mQueue变量:

Looper.myLooper()是这样的:

1
2
3
4
5
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}

从装有Looper对象的ThreadLocal中取出一个Looper返回。那么取出来的是哪一个Looper那?我们看一下ThreadLocal的get()方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public T get() {
// Optimized for the fast path.
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.

1
mQueue = mLooper.mQueue;

通过上面这句我们知道MessageQueue是在Looper中的。

1
2
3
4
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}

在Looper的私有构造函数中初始化了一个MessageQueue对象。

Looper不断循环MessageQueue中的Message:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;

// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();

for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}

// This must be in a local variable, in case a UI event sets the logger
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}

msg.target.dispatchMessage(msg);//看这里

if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}

// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}

msg.recycleUnchecked();
}
}

msg.target返回一个Handler对象。调用Handler的dispatchMessage()方法:

1
2
3
4
5
6
7
8
9
10
11
12
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);//看这里
}
}

在dispatchMessage方法中又回调了handleMessage(msg)方法


结论:

  • 主线程默认有自己的Looper
  • Looper在不断死循环MessageQueue
  • 死循环中msg.target.dispatchMessage(msg);通过Message将消息扔给Handler
  • 回调Handler的handleMessage方法完成处理
文章目录
  1. 1. 一、概述:
    1. 1.1. Android中太多的东西和Handler-Looper有关了(HandlerThread,IntentService),要想了解他们必须把Handler基础掌握,之前对Handler了解了不知道多少遍,今天终于看了一下源码。还好Handler,Looper,MessageQueue都没有很深的继承结构,代码量也不多,所以看起来比较轻松好理解。
  2. 2. 二、从基本的使用开始说起:
    1. 2.1. 1、首先new一个Handler调用构造函数:
      1. 2.1.1. 1.1在代码中我们看到初始化了mLooper变量和mQueue变量:
      2. 2.1.2. Looper.myLooper()是这样的:
      3. 2.1.3. 从装有Looper对象的ThreadLocal中取出一个Looper返回。那么取出来的是哪一个Looper那?我们看一下ThreadLocal的get()方法
    2. 2.2. 我们可以确定取出的是当前线程的Looper.
      1. 2.2.1. 通过上面这句我们知道MessageQueue是在Looper中的。
      2. 2.2.2. 在Looper的私有构造函数中初始化了一个MessageQueue对象。
    3. 2.3. Looper不断循环MessageQueue中的Message:
    4. 2.4. msg.target返回一个Handler对象。调用Handler的dispatchMessage()方法:
    5. 2.5. 在dispatchMessage方法中又回调了handleMessage(msg)方法
  3. 3. 结论: