Android消息处理流程(handler)

说到消息的处理流程就要涉及到Handler、Message、MessageQueue、Looper、HandlerThread这几个类:

  • Handler的作用有两个:在新线程中发送消息,在主线程中接受并处理消息。通过handler发送的消息必须被送入到指定的MessageQueue中,所以当前线程中必须有一个MessageQueue对象。MessageQueue对象是在Looper的构造方法中创建的
  • MessageQueue:消息队列,负责对消息进行管理。
  • Looper:负责管理MessageQueue中的消息
    如果是主线程:系统已经初始化了一个Looper对象,程序直接创建Handler,就可以通过hangler发送消息了。
    如果是子线程:必须手动创建Looper对象并启动它。创建Looper对象调用Looper的prepare方法即可,通过looper的loop方法启动。

下面我们就从消息的创建开始介绍消息的处理流程。

一.消息的创建:

借助Message类的obtain方法创建消息

Message message = Message.obtain();
message.what = POST;
message.obj = response.body().string();

二.消息的发送:send和post

不管是调用send类型的哪个方法,都会首先调用sendMessageDelayed方法,然后sendMessageDelayed中又会调用sendMessageAtTime方法。而post类型的方法又是对send类型的方法的封装。

send类型的方法:

public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
public final boolean sendEmptyMessage(int what)
    {
        return sendEmptyMessageDelayed(what, 0);
    }
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, delayMillis);
    }
public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageAtTime(msg, uptimeMillis);
    }
public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return 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);
    }
public final boolean sendMessageAtFrontOfQueue(Message msg) {
        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, 0);
    }                        

post类型的方法

public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }
public final boolean postAtTime(Runnable r, long uptimeMillis)
    {
        return sendMessageAtTime(getPostMessage(r), uptimeMillis);
    }
public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
    {
        return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
    }
public final boolean postDelayed(Runnable r, long delayMillis)
    {
        return sendMessageDelayed(getPostMessage(r), delayMillis);
    }
public final boolean postAtFrontOfQueue(Runnable r)
    {
        return sendMessageAtFrontOfQueue(getPostMessage(r));
    }                

而在sendMessageAtTime方法中又会调用enqueueMessage方法:
这个方法中的mQueue是通过与Handler有关的Looper获得的。

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

下面来看enqueueMessage方法,在enqueueMessage方法中将Message的target设置为当前的handler并将Message添加到消息队列。

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

三.消息的接受

一方面我们将message添加到MessageQueue,另一方面HandlerThread类中的run方法开始执行:
我们重点看 Looper.prepare()和Looper.loop()

public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }

Looper.prepare()方法:prepare中先判断当前线程中是否已经存在Looper对象,如果不存在则用new Looper创建Looper对象,从而保证当前线程中只有一个Looper对象。

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

接下来我们来看Looper的构造函数:
可以看到在Looper的构造函数中创建了MessageQueue对象,所以当前线程中Looper对象的唯一性保证了MessageQueue对象的唯一性。

private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

然后看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
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

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

我们重点看for循环中的内容:
1.Message msg = queue.next();
在循环中不断的调用MessageQueue的next方法取出消息队列中的消息。
2.调用msg.target.dispatchMessage(msg);方法,按照发送消息时target的不同将消息交给不同的handler处理,target就是发送message时跟message关联的handler,也就是执行我们重写的Handler类的handleMessage方法。
3.最后对消息进行回收。

Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 100:

                    break;
                case 200:

                    break;
            }
            super.handleMessage(msg);
        }
    };

你可能感兴趣的:(Android基础)