1、消息对象的创建
a.在Handler.java中的obtainMessage方法,最终都是调用了Message.obtain(this)放法。
b.Message.java中的所有的obtain方法的重载 最终都是调用了无参的obtain()方法。
//这个方法 如果消息池里面没有消息,就new出来,如果有,就取出第一条给你
public static Message obtain() {
synchronized (mPoolSync) {
if (mPool != null) {
Message m = mPool;
mPool = m.next;
m.next = null;
return m;
}
}
return new Message();
}
```
### 2、Handler的创建
a. 在Handler.java中看Handler的无参方法
public Handler() {
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());
}
}
//你在new一个handler的时候 拿到主线程的轮循器
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 = null;
}
```
b. 轮训器的得到 点进myLooper方法 在Looper.java类中
public static final Looper myLooper() {
//有get() 就可以看 是在哪里把Looper对象放进sThreadLocal来的
return (Looper)sThreadLocal.get();
}
```
c. 查看在哪里set的
public static final void prepare() {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//消息轮训器是直接new出来的
sThreadLocal.set(new Looper());
}
private Looper() {
//在newLooper的构造方法里面 把消息队列也new了出来
mQueue = new MessageQueue();
mRun = true;
mThread = Thread.currentThread();
}
```
d. 轮训器和消息队列都是在prepare()方法调用的时候new的 那么prepare方法什么时候调用呢
主线程创建并启动的时候 调用这个方法
public static final void prepareMainLooper() {
//preparMainLooper方法调用prepare()
prepare();
setMainLooper(myLooper());
if (Process.supportsProcesses()) {
myLooper().mQueue.mQuitAllowed = false;
}
}
```
e. **ActivityThread(所有应用的主线程)**
public static final void main(String[] args) {
SamplingProfilerIntegration.start();
Process.setArgV0("");
Looper.prepareMainLooper();
if (sMainThreadHandler == null) {
sMainThreadHandler = new Handler();
}
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
if (Process.supportsProcesses()) {
throw new RuntimeException("Main thread loop unexpectedly exited");
}
thread.detach();
String name = (thread.mInitialApplication != null)
? thread.mInitialApplication.getPackageName()
: "";
Slog.i(TAG, "Main thread of " + name + " is now exiting");
}
```
f. 查看loop
public static final void loop() {
Looper me = myLooper();
MessageQueue queue = me.mQueue;
while (true) {
//有消息就取 没消息可能会阻塞 进入休眠
//什么时候醒过来,子线程发送消息到消息队列,然后向管道文件写一写数据 就醒过来
//读完消息,就分发
Message msg = queue.next(); // might block
//if (!me.mRun) {
// break;
//}
if (msg != null) {
if (msg.target == null) {
// No target is a magic identifier for the quit message.
return;
}
if (me.mLogging!= null) me.mLogging.println(
">>>>> Dispatching to " + msg.target + " "
+ msg.callback + ": " + msg.what
);
//分发消息
//target指的是创建msg对象的handler对象 谁发送 谁处理。
//在obtainMessage创建消息时,把this(自己传过去)
//接收到this后 直接把target等于传过来的handler对象。
msg.target.dispatchMessage(msg);
if (me.mLogging!= null) me.mLogging.println(
"<<<<< Finished to " + msg.target + " "
+ msg.callback);
msg.recycle();
}
}
}
```
g. 在Handler.java中
//在obtainMessage创建消息时,把this(自己传过去)
public final Message obtainMessage()
{
return Message.obtain(this);
}
```
h. 在Message.java中
//接收到this后 直接把target等于传过来的handler对象。
public static Message obtain(Handler h) {
Message m = obtain();
m.target = h;
return m;
}
3、Looper分发处理消息
a. 发消息最后跳到sendMessageAtTime(Message msg, long uptimeMillis) 无论以什么方式发送消息(handler.sendMessage(msg) 或者handler.sendEmptyMessageDelayed(msg,time)等)最终调用的都是**sendMessageAtTime(Message msg, long uptimeMillis) **
public boolean sendMessageAtTime(Message msg, long uptimeMillis)
{
boolean sent = false;
MessageQueue queue = mQueue;
if (queue != null) {
msg.target = this;
//这个方法就是把消息放到消息队列
sent = queue.enqueueMessage(msg, uptimeMillis);
}
else {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
}
return sent;
}
```
b.enqueueMessage()
final boolean enqueueMessage(Message msg, long when) {
if (msg.when != 0) {
throw new AndroidRuntimeException(msg
+ " This message is already in use.");
}
if (msg.target == null && !mQuitAllowed) {
throw new RuntimeException("Main thread not allowed to quit");
}
final boolean needWake;
synchronized (this) {
if (mQuiting) {
RuntimeException e = new RuntimeException(
msg.target + " sending message to a Handler on a dead thread");
Log.w("MessageQueue", e.getMessage(), e);
return false;
} else if (msg.target == null) {
mQuiting = true;
}
msg.when = when;
//Log.d("MessageQueue", "Enqueing: " + msg);
Message p = mMessages;
if (p == null || when == 0 || when < p.when) {
msg.next = p;
mMessages = msg;
needWake = mBlocked; // new head, might need to wake up
} else {
Message prev = null;
while (p != null && p.when <= when) {
prev = p;
p = p.next;
}
msg.next = prev.next;
prev.next = msg;
needWake = false; // still waiting on head, no need to wake up
}
}
if (needWake) {
nativeWake(mPtr);
}
return true;
}
public void handleMessage(Message msg) {
//方法体为空 有程序员处理
}
```
c. 回调handleMessage�方法
/** * Handle system messages here. */ //这里面调用handleMessage(msg)方法 public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }