本文共 14106 字,大约阅读时间需要 47 分钟。
异步通信,消息传递
public class HandlerActivity extends AppCompatActivity {Handler handler = new Handler() { @Override public void handleMessage(Message msg) { Toast.makeText(HandlerActivity.this, "接收到了消息", Toast.LENGTH_SHORT).show(); }};@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_handler);}public void onClickView(View v) { switch (v.getId()) { case R.id.button: { Thread thread = new Thread() { @Override public void run() { Message msg = Message.obtain(); handler.sendMessage(msg); } }; thread.start(); break; } }}}
这个界面只有一个Button, 点击事件是:启动一个线程,在这个线程里使用handler,发送一个消息;这个消息不带任何数据。
Message: 这个可以使用new来生成,但是最好还是使用Message.obtain()来获取一个实例。这样便于消息池的管理。 handler初始化的时候,我们复写了handleMessage方法,这个方法用来接收,子线程中发过来的消息。public class HandlerActivity extends AppCompatActivity {Handler handler = new Handler() { @Override public void handleMessage(Message msg) { Log.d("child", "----" + Thread.currentThread().getName()); }};Handler childHandler = null;@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_handler); Thread child = new Thread("child thread") { @Override public void run() { Looper.prepare(); childHandler = new Handler(Looper.myLooper()) { @Override public void handleMessage(Message msg) { Log.d("child", "----" + Thread.currentThread().getName() + ", " + msg.obj); } }; Looper.loop(); } }; child.start();}public void onClickView(View v) { switch (v.getId()) { case R.id.button: { Thread thread = new Thread() { @Override public void run() { Message msg = Message.obtain(); handler.sendMessage(msg); } }; thread.start(); break; } case R.id.button1: { if (childHandler != null) { Message msg = Message.obtain(childHandler); msg.obj = "123---" + SystemClock.uptimeMillis(); childHandler.sendMessage(msg); } else { Log.d("-----", "onClickView: child Handler is null"); } break; } }}}
主线程向子线程发送消息时,我们需要使用的是handler,但是这个handler是需要在子线程中实例化,否则子线程无法接收到消息。
在child thread中准备的工作:Looper.loop()调用
假如我们直接在子线程中直接实例化一个handler,而不传入Looper实例。程序会直接抛出异常:java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
这个异常是在hanlder源码: 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();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; } 出现的,从这里可知,在线程中实例化一个handler需要一个Looper实例。首先看Looper源码中是怎么写的。Looper的构造方法是私有的,这样我们只能通过Looper的静态方法来实例化一个Looper.在Looper类中还有一个ThreadLocal<Looper> sThreadLocal 变量,而在上面的代码中使用了Looper.myLooper()方法来给handler一个Looper实例。
public static @Nullable Looper myLooper() {return sThreadLocal.get();}
这个方法返回了一个存放在ThreadLocal<Looper>中的Looper实例。
Looper.prepare源码:
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"); } sThreadLocal.set(new Looper(quitAllowed)); } 方法很简单,就是检查sThreadLocal里面是否有有值,然后将Looper的实例存放到ThreadLocal,如果不为空,直接就是 RuntimeException 异常。这也保证了一个线程中只能有一个Looper实例。因此,Looper.prepare方法只能调用一次。在这个程序中,可以大概理解成线程间数据的隔离。意思就是我存放在ThreadLocal中的数据,只能在我本线程中可以获得到值,在其他线程中获取不到(其他线程中获取的是null)。
这样就能得出,其他线程中的Looper,在本线程中通过Looper.myLooper()获取不到数据。通过查找Android源码,可以知道在ActivityThread中main方法里面,UI线程已经初始化了Looper.prepareMainLooper();这样就在UI线程中有Looper实例了。当然在main方法的下面,也调用了Looper.loop()方法。
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 final Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs; final long traceTag = me.mTraceTag; if (traceTag != 0 && Trace.isTagEnabled(traceTag)) { Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); } final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); final long end; try { msg.target.dispatchMessage(msg); end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } if (slowDispatchThresholdMs > 0) { final long time = end - start; if (time > slowDispatchThresholdMs) { Slog.w(TAG, "Dispatch took " + time + "ms on " + Thread.currentThread().getName() + ", h=" + msg.target + " cb=" + msg.callback + " msg=" + msg.what); } } 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.dispatchMessage(msg);
for循环是一个死循环,这个需要一直取出MessageQueue队列中的数据,也就是刚才所列的第三个 queue.next方法。这个方法会阻塞,直到有消息从消息队列中取出来。
next方法源码: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.final long ptr = mPtr;if (ptr == 0) { return null;}int pendingIdleHandlerCount = -1; // -1 only during first iterationint nextPollTimeoutMillis = 0;for (;;) { if (nextPollTimeoutMillis != 0) { Binder.flushPendingCommands(); } nativePollOnce(ptr, nextPollTimeoutMillis); synchronized (this) { // Try to retrieve the next message. Return if found. final long now = SystemClock.uptimeMillis(); Message prevMsg = null; Message msg = mMessages; if (msg != null && msg.target == null) { // Stalled by a barrier. Find the next asynchronous message in the queue. do { prevMsg = msg; msg = msg.next; } while (msg != null && !msg.isAsynchronous()); } if (msg != null) { if (now < msg.when) { // Next message is not ready. Set a timeout to wake up when it is ready. nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE); } else { // Got a message. mBlocked = false; if (prevMsg != null) { prevMsg.next = msg.next; } else { mMessages = msg.next; } msg.next = null; if (DEBUG) Log.v(TAG, "Returning message: " + msg); msg.markInUse(); return msg; } } else { // No more messages. nextPollTimeoutMillis = -1; } // Process the quit message now that all pending messages have been handled. if (mQuitting) { dispose(); return null; } // If first time idle, then get the number of idlers to run. // Idle handles only run if the queue is empty or if the first message // in the queue (possibly a barrier) is due to be handled in the future. if (pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)) { pendingIdleHandlerCount = mIdleHandlers.size(); } if (pendingIdleHandlerCount <= 0) { // No idle handlers to run. Loop and wait some more. mBlocked = true; continue; } if (mPendingIdleHandlers == null) { mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)]; } mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers); } // Run the idle handlers. // We only ever reach this code block during the first iteration. for (int i = 0; i < pendingIdleHandlerCount; i++) { final IdleHandler idler = mPendingIdleHandlers[i]; mPendingIdleHandlers[i] = null; // release the reference to the handler boolean keep = false; try { keep = idler.queueIdle(); } catch (Throwable t) { Log.wtf(TAG, "IdleHandler threw exception", t); } if (!keep) { synchronized (this) { mIdleHandlers.remove(idler); } } } // Reset the idle handler count to 0 so we do not run them again. pendingIdleHandlerCount = 0; // While calling an idle handler, a new message could have been delivered // so go back and look again for a pending message without waiting. nextPollTimeoutMillis = 0;}
}
public void dispatchMessage(Message msg) {<br/>if (msg.callback != null) {<br/>handleCallback(msg);<br/>} else {<br/>if (mCallback != null) {<br/>if (mCallback.handleMessage(msg)) {<br/>return;<br/>}<br/>}<br/>handleMessage(msg);<br/>}<br/>}<br/>
Handler初始化的时候,我们并没有传入msg.callback和mCallback这两个回调。所以这个方法最终执行的是handleMessage方法。 上面我们分析了ThreadLocal,Looper,Message,MessageQueue,下面开始分析handler发送消息的方式。 Handler 通过sendMessage方法发送消息。这个方法最终调用的是
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {<br/>msg.target = this;<br/>if (mAsynchronous) {<br/>msg.setAsynchronous(true);<br/>}<br/>return queue.enqueueMessage(msg, uptimeMillis);<br/>}<br/>
boolean enqueueMessage(Message msg, long 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(TAG, e.getMessage(), e); msg.recycle(); return false; } 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); } } return true;}
通过handler发送Message,将Message压入MessageQueue队列中;而Looper.loop方法又在不停的循环这个消息队列,取出压入MessageQueue的Message, 然后dispatchMessage分发,最终会调用handler.handleMessage方法来处理发送过来的Message.
本文转自 墨宇hz 51CTO博客,原文链接:http://blog.51cto.com/zzhhz/2045446
转载地址:http://gdovx.baihongyu.com/