在网上看了侃哥的视频,详细记录一下.
对Handler机制的理解,可以分成四个部分,消息的创建,Handler的创建,消息的发送,消息的处理。
源码基本上都是基于2.3的源码(相对比较好理解),部分会做一下比较。
1、消息的创建 handler调用obtainMessage
public final Message obtainMessage(){// 这个this就是handlerreturn Message.obtain(this);}
//其实消息还是Message自己创建的public static Message obtain(Handler h) {// 调用自身的obtain方法Message m = obtain();// 同时将targer指向handler 其他重载方法也是一样m.target = h;return m;}
public static Message obtain() {synchronized (sPoolSync) {if (sPool != null) {// 如果有消息 直接赋给m 没有的话 创建一个新的消息Message m = sPool;// Message内部自己维护消息sPool = m.next;m.next = null;sPoolSize--;return m;}}return new Message();}
//recycleUnchecked()方法synchronized (sPoolSync) {if (sPoolSize < MAX_POOL_SIZE) {next = sPool;sPool = this;sPoolSize++;}}
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());}}// 从Looper对象中获取,所以使用Handler必须要先有Looper// 在prepare方法中,会判断有没有looper绑定到当前线程,没有的话 new一个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;}
// 2.3 源码中有无参的构造函数 新的似乎被隐藏了private Looper() {mQueue = new MessageQueue();mRun = true;mThread = Thread.currentThread();}
private static void prepare(boolean quitAllowed) {// 如果已经执行过prepare方法,那么会报异常,// 没有的话 创建一个 new Looper 并绑定到当前线程 此时线程中就有了一个Loooer对象// 参见构造函数if (sThreadLocal.get() != null) {throw new RuntimeException("Only one Looper may be created per thread");}// 2.3的源码构造函数是没有参数的 5.1源码,隐藏了构造函数// 但肯定还是基于2.3源码的 Looper初始化的时候,有一个消息队列对象sThreadLocal.set(new Looper(quitAllowed));}
public final class ActivityThread
public static final void main(String[] args) {SamplingProfilerIntegration.start();Process.setArgV0("<pre-initialized>");Looper.prepareMainLooper();if (sMainThreadHandler == null) {sMainThreadHandler = new Handler();}ActivityThread thread = new ActivityThread();thread.attach(false);if (false) {Looper.myLooper().setMessageLogging(newLogPrinter(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(): "<unknown>";Slog.i(TAG, "Main thread of " + name + " is now exiting");}}
public final boolean sendMessageDelayed(Message msg, long delayMillis){if (delayMillis < 0) {delayMillis = 0;}//msg的whenreturn 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) {msg.target = this;if (mAsynchronous) {msg.setAsynchronous(true);}// 去排队return queue.enqueueMessage(msg, uptimeMillis);}
boolean enqueueMessage(Message msg, long when) {// when --》 数值越小 越靠前if (msg.target == null) {throw new IllegalArgumentException("Message must have a target.");}if (msg.isInUse()) {throw new IllegalStateException(msg + " This message is already in use.");}synchronized (this) {if (mQuitting) {IllegalStateException e = new IllegalStateException(msg.target + " sending message to a Handler on a dead thread");Log.w("MessageQueue", e.getMessage(), e);msg.recycle();return false;}msg.markInUse();msg.when = when;//mMessages 消息队列里的第一条消息Message p = mMessages;boolean needWake;// 如果消息队列里的第一条消息为null 或者。。。那么发过来的就是第一条消息 同时next只能等于null// 第二种情况:时间如果是0,说明消息需要优先处理,同样将发过来的消息放在第一条,而msg.next = p;就把传入的msg的next设置为原来的第一条( Message p = mMessages;)// 第三种情况:传入消息的时间,小于第一条消息的时间,仍然要优先运行。if (p == null || when == 0 || when < p.when) {// New head, wake up the event queue if blocked.msg.next = p;mMessages = msg;needWake = mBlocked;} else {// Inserted within the middle of the queue. Usually we don't have to wake// up the event queue unless there is a barrier at the head of the queue// and the message is the earliest asynchronous message in the queue.needWake = mBlocked && p.target == null && msg.isAsynchronous();Message prev;// 2.3 的源码是用while()for (;;) {// prev指向第一条 p指向下一条prev = p;p = p.next;// 如果没有下一条或者时间小于下一条的时间 跳出(顺序正确) 换下一条 没有下一条 跳出if (p == null || when < p.when) {break;}if (needWake && p.isAsynchronous()) {// 是否需要唤醒主线程 通常第一条才(可能)需要(也需要一些运算) 不是第一条就不用needWake = false;}}// 跟消息队列的消息比较 找到传入消息对应的插入位置// 例如队列里有ABC 三条消息, 假设都是按顺序的,那么当p走到C的时候,根据上面prev=p p=p.next的时候,// prev 就是C C.next是null 跳出 那么传入的消息就插在最后,C的.next指向传入的消息msg.next = p; // invariant: p == prev.nextprev.next = msg;}// We can assume mPtr != 0 because mQuitting is false.if (needWake) {nativeWake(mPtr);}}return true;}
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;}
private native static long nativeInit();private native static void nativeDestroy(long ptr);private native static void nativePollOnce(long ptr, int timeoutMillis);private native static void nativeWake(long ptr);private native static boolean nativeIsIdling(long ptr);
static void android_os_MessageQueue_nativeInit(JNIEnv* env, jobject obj) {NativeMessageQueue* nativeMessageQueue = new NativeMessageQueue();if (! nativeMessageQueue) {jniThrowRuntimeException(env, "Unable to allocate native queue");return;}// 返回值?android_os_MessageQueue_setNativeMessageQueue(env, obj, nativeMessageQueue);}static void android_os_MessageQueue_setNativeMessageQueue(JNIEnv* env, jobject messageQueueObj, NativeMessageQueue* nativeMessageQueue) {env->SetIntField(messageQueueObj, gMessageQueueClassInfo.mPtr, reinterpret_cast<jint>(nativeMessageQueue));}
static void android_os_MessageQueue_nativeDestroy(JNIEnv* env, jobject obj) {NativeMessageQueue* nativeMessageQueue =android_os_MessageQueue_getNativeMessageQueue(env, obj);if (nativeMessageQueue) {android_os_MessageQueue_setNativeMessageQueue(env, obj, NULL);delete nativeMessageQueue;}}
static void android_os_MessageQueue_nativeWake(JNIEnv* env, jobject obj, jint ptr) {//reinterpret_cast是一个强类型指针,将整形转化成指针 ptr在MessageQueue中 是通过nativeInit()得到的NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);return nativeMessageQueue->wake();}
class NativeMessageQueue {public:NativeMessageQueue();~NativeMessageQueue();inline sp<Looper> getLooper() { return mLooper; }void pollOnce(int timeoutMillis);void wake();private:sp<Looper> mLooper;};
NativeMessageQueue::NativeMessageQueue() {mLooper = Looper::getForThread();if (mLooper == NULL) {mLooper = new Looper(false);Looper::setForThread(mLooper);}}NativeMessageQueue::~NativeMessageQueue() {}void NativeMessageQueue::pollOnce(int timeoutMillis) {mLooper->pollOnce(timeoutMillis);}void NativeMessageQueue::wake() {mLooper->wake();}
void Looper::wake() {#if DEBUG_POLL_AND_WAKELOGD("%p ~ wake", this);#endif#ifdef LOOPER_STATISTICS// FIXME: Possible race with awoken() but this code is for testing only and is rarely enabled.if (mPendingWakeCount++ == 0) {mPendingWakeTime = systemTime(SYSTEM_TIME_MONOTONIC);}#endifssize_t nWrite;do {// 写了一个W 到管道中 用于唤醒主线程nWrite = write(mWakeWritePipeFd, "W", 1);} while (nWrite == -1 && errno == EINTR);if (nWrite != 1) {if (errno != EAGAIN) {LOGW("Could not write wake signal, errno=%d", errno);}}}
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();// 2.3的源码这里是while(true)for (;;) {// linux底层采用epoll的方式 等待唤醒Message msg = queue.next(); // might blockif (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 loggerPrinter logging = me.mLogging;if (logging != null) {logging.println(">>>>> Dispatching to " + msg.target + " " +msg.callback + ": " + msg.what);}// 如果有消息,分发消息// msg.target 就是发送该消息的handler// 线程中可以有多个Handler,使用绑定的target就可以保证,是哪个Handler发送的消息// 就由哪个Handler处理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();}}
/*** Handle system messages here.*/public void dispatchMessage(Message msg) {// 如果使用了post(Runnable r)的话 会将r绑定在一个消息上发送 callback就有值,callback就是一个Runnableif (msg.callback != null) {handleCallback(msg);} else {// handler内部封装了一个接口 Callback 不过看起来只在Handler的隐藏构造方法中赋值,所以一般为空// 为空的话,就调用复写的handlerMessage方法if (mCallback != null) {if (mCallback.handleMessage(msg)) {return;}}// 需要复写的方法handleMessage(msg);}}
/*** Callback interface you can use when instantiating a Handler to avoid* having to implement your own subclass of Handler.** @param msg A {@link android.os.Message Message} object* @return True if no further handling is desired*/public interface Callback {public boolean handleMessage(Message msg);}
191




被折叠的 条评论
为什么被折叠?



