Toast.makeText(mContext, "I'm new Thread !", Toast.LENGTH_SHORT).show();
} }).start();
结果很明显,程序一启动立刻就奔溃了。并抛出异常java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()。 于是乎我又在try block 之前添加了Looper.prepare()这行代码。再次运行程序虽然没有奔溃,但也没有任何反应,Toast也没显示。
publicint what; publicint arg1; publicint arg2; public Object obj; /*package*/ Handler target; /*package*/ Runnable callback; /** * Return a new Message instance from the global pool. Allows us to * avoid allocating new objects in many cases. */ publicstatic 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; } } returnnew Message(); } /** Constructor (but the preferred way to get a Message is to call {@link #obtain() Message.obtain()}). */ publicMessage(){ } }
Message next(){ // Return here if the message loop has already quit and been disposed. // This can happen if the application tries to restart a looper after quit // which is not supported. finallong ptr = mPtr; if (ptr == 0) { returnnull; } …… } ``` *由于这个方法中有一些native调用,未能完全理解,只知道会返回一个Message对象。*
privatestaticvoidprepare(boolean quitAllowed){ if (sThreadLocal.get() != null) { thrownew RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(quitAllowed)); }
publicstaticvoidloop(){ final Looper me = myLooper(); if (me == null) { thrownew RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final MessageQueue queue = me.mQueue; for (;;) { Message msg = queue.next(); // might block if (msg == null) { // No message indicates that the message queue is quitting. return; } msg.target.dispatchMessage(msg); msg.recycleUnchecked(); } }
首先看第一句代码执行的方法:
1 2 3 4 5 6 7
/** * Return the Looper object associated with the current thread. Returns * null if the calling thread is not associated with a Looper. */ publicstatic@NullableLooper myLooper(){ return sThreadLocal.get(); }
publicHandler(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(); if (mLooper == null) { thrownew RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; }
publicbooleansendMessageAtTime(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); returnfalse; } return enqueueMessage(queue, msg, uptimeMillis); }
经过之前的构造方法,mQueue显然不为null,继续往下看
1 2 3 4 5 6 7
privatebooleanenqueueMessage(MessageQueue queue, Message msg, long uptimeMillis){ msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
booleanenqueueMessage(Message msg, long when){ if (msg.target == null) { thrownew IllegalArgumentException("Message must have a target."); } if (msg.isInUse()) { thrownew 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(TAG, e.getMessage(), e); msg.recycle(); returnfalse; }
msg.markInUse(); msg.when = when; Message p = mMessages; boolean needWake; 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; for (;;) { prev = p; p = p.next; if (p == null || when < p.when) { break; } if (needWake && p.isAsynchronous()) { needWake = false; } } msg.next = p; // invariant: p == prev.next prev.next = msg; }
// We can assume mPtr != 0 because mQuitting is false. if (needWake) { nativeWake(mPtr); } } returntrue; }
到了这里,我们终于明白了,使用Handler 的postDelay 方法时,其Runnable中的run方法并不是在子线程中执行,而是把这个Runnable赋值给了一个Message对象的callback属性,而这个Message会被传递到创建Handler所在的线程,也就是这里的主线程,所以这个Toast的显示依旧是在主线程中。这也和postDelay API 中所声明的内容是一致的。
/** * Causes the Runnable r to be added to the message queue, to be run * after the specified amount of time elapses. * The runnable will be run on the thread to which this handler * is attached. */