了解Handler,Looper, MessageQueue,Message的工作流程

简介:

Handler的作用

异步通信,消息传递

Handler的基本用法

Handler的用法,示例1、(子线程向主线程发送消息)

public class HandlerActivity extends AppCompatActivity {
Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        Toast.makeText(HandlerActivity.this, "接收到了消息", Toast.LENGTH_SHORT).show();
    }
};
@Override
protected 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方法,这个方法用来接收,子线程中发过来的消息。

示例2、主线程向子线程发送消息

public class HandlerActivity extends AppCompatActivity {
Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        Log.d("child", "----" + Thread.currentThread().getName());
    }
};
Handler childHandler = null;

@Override
protected 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中准备的工作:

    1. Looper.prepare();
    1. 实例化childHandler的时候出入了一个Looper实例。
    1. 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.在Looper类中还有一个ThreadLocal<Looper> sThreadLocal 变量,而在上面的代码中使用了Looper.myLooper()方法来给handler一个Looper实例。

      * Looper.myLooper()

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

      这个方法返回了一个存放在ThreadLocal<Looper>中的Looper实例。

      为什么在调用Looper.myLooper()方法之前需要先调用 Looper.prepare()呢?

      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的作用是什么呢?

    在这个程序中,可以大概理解成线程间数据的隔离。意思就是我存放在ThreadLocal中的数据,只能在我本线程中可以获得到值,在其他线程中获取不到(其他线程中获取的是null)。
    这样就能得出,其他线程中的Looper,在本线程中通过Looper.myLooper()获取不到数据。

    那么为什么在主线程中不需要传入Looper实例呢?

    通过查找Android源码,可以知道在ActivityThread中main方法里面,UI线程已经初始化了Looper.prepareMainLooper();这样就在UI线程中有Looper实例了。当然在main方法的下面,也调用了Looper.loop()方法。

    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();
    **}**

    }

这个方法里面,我们需要注意到:

  1. Looper me这个不允许为空
  2. for (;;)循环
  3. Message msg = queue.next()
  4. msg.target.dispatchMessage(msg);

  5. 在looper.loop方法里面,检查了本线程中的Looper实例,也对应了在调用looper.loop方法之前必须先调用looper.prepare方法。
  6. 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 iteration
    int 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;
    }

    }

  7. queue.next方法,返回一个Message,而这个message会被传入到msg.target的dispatchMessage方法中。msg.target是一个handler,就是发送消息的实例。
    dispatchMessage(Message)源码:
    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发送消息

    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/>
参数:MessageQueue queue则是Handler中mQueue变量,这个变量在Handler(Callback callback, boolean async)初始化完成。它是Looper中一个final MessageQueue的变量,在初始化Looper的时候,就开始初始化MessageQueue。这也是一个线程中只有一个MessageQueue的原因.
Message msg 是封装的消息。
long uptimeMillis 延迟发送时间。
之前分析looper.loop方法的时候,说了msg.target.dispatchMessage, 这个target就是在这个方法里面赋值的。
从这个方法里面,可以知道handler的sendMessage,只是把消息(Message实例)添加到了queue队列中。

    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, Looper, Message, MessageQueue之间的关系

通过handler发送Message,将Message压入MessageQueue队列中;而Looper.loop方法又在不停的循环这个消息队列,取出压入MessageQueue的Message, 然后dispatchMessage分发,最终会调用handler.handleMessage方法来处理发送过来的Message.


本文转自 墨宇hz 51CTO博客,原文链接:http://blog.51cto.com/zzhhz/2045446


相关文章
|
1月前
|
消息中间件 存储 Java
Android消息处理机制(Handler+Looper+Message+MessageQueue)
Android消息处理机制(Handler+Looper+Message+MessageQueue)
45 2
|
6月前
|
Java Android开发
Android之Handler、Message、MessageQueue、Looper详解1
Android之Handler、Message、MessageQueue、Looper详解
57 0
|
6月前
|
消息中间件 安全 数据处理
Android之Handler、Message、MessageQueue、Looper详解2
Android之Handler、Message、MessageQueue、Looper详解
81 0
|
消息中间件 存储 项目管理
handler+message【消息机制】
handler+message【消息机制】
179 0
handler+message【消息机制】
|
消息中间件 Java Android开发
Android Handler 机制 - Looper,Message,MessageQueue
Android Studio 2.3 API 25 从源码角度分析Handler机制。有利于使用Handler和分析Handler的相关问题。 Handler 简介 一个Handler允许发送和处理Message,通过关联线程的 MessageQueue 执行 Runnable 对象。
1533 0
|
消息中间件 Java Android开发
【Android 异步操作】手写 Handler ( 总结 | Message | MessageQueue | Looper | Handler ) ★(二)
【Android 异步操作】手写 Handler ( 总结 | Message | MessageQueue | Looper | Handler ) ★(二)
146 0
|
消息中间件 存储 Android开发
【Android 异步操作】手写 Handler ( 总结 | Message | MessageQueue | Looper | Handler ) ★(一)
【Android 异步操作】手写 Handler ( 总结 | Message | MessageQueue | Looper | Handler ) ★(一)
108 0
|
消息中间件 存储 Java
【Android 异步操作】手写 Handler ( Message 消息 | ThreadLocal 线程本地变量 | Looper 中的消息队列 MessageQueue )
【Android 异步操作】手写 Handler ( Message 消息 | ThreadLocal 线程本地变量 | Looper 中的消息队列 MessageQueue )
170 0
|
消息中间件 存储 机器学习/深度学习
【Android】Handler 机制 ( Handler | Message | Looper | MessageQueue )(二)
【Android】Handler 机制 ( Handler | Message | Looper | MessageQueue )(二)
140 0
|
消息中间件 存储 调度
【Android】Handler 机制 ( Handler | Message | Looper | MessageQueue )(一)
【Android】Handler 机制 ( Handler | Message | Looper | MessageQueue )(一)
177 0