Android中的Handler消息机制

在Android开发中,是不能在子线程中更新UI的,这一点想必大家都知道,但是,很多时候在子线程中访问了网络或做其它耗时处理后,希望可以把结果更新到UI中。于是,Android 中提供了一个Handler机制。它很好的解决了这个问题。

在分析Handler之前,先简单说下几个关键类:

  • Handler:负责消息的发送和处理。
  • Message:消息载体,用于保存消息的arg、内容等。
  • MessageQueue:消息队列,用于存放消息载体Message。
  • Looper:可以看成是一个消息轮询器,会不断的从MessageQueue中取出Message
Android中的Handler消息机制_第1张图片
Android消息机制.png

1、Handler的使用

private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            
            if(msg.what == 1){
                //接收消息并处理
            }
        }
    };

new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = Message.obtain();
                message.what = 1;
                message.obj = "消息";
                handler.sendMessage(message);
            }
        }).start();

从代码看,Handler的使用很简单,在子线程中创建一个Message对象,通过handler.sendMessage()发送,然后在Handler内的handleMessage()中进行处理。但是,在实际开发中创建Handler时,建议大家选用以静态内部类的方式来创建Handler,这样可以降低内存泄漏的发生。接下来看一下Handler的构造函数。

 public Handler() {
        this(null, false);
    }

public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class 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();
        //1
        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;
    }

在第二个构造函数注释1处,可以发现:如果当前线程中mLooper 为null,会抛出RuntimeException,这也就是为什么在子线程中创建Handler需要先Looper.prepare()的原因。而主线程不用我们手动创建Looper对象,是因为在启动程序时已经为主线程创建了Looper对象。看下面一段ActivityThread类中的main方法:

public static void main(String[] args) {
        //省略代码...........
        //为主线程创建一个Looper对象
        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
         //启动消息轮询
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

在程序启动时,不单单是为主线程创建了一个Looper对象,而且还启动的消息轮询器Looper.loop()。接下来我们先分析sendMessage(),看看消息是怎么加进MessageQueue中的。

2、sendMessage()分析

public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

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

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

通过上面一系列代码下来,可以发现:sendMessage()发送消息后,最后会调用MessageQueue的enqueueMessage()方法,uptimeMillis是发送消息的时间。

//MessageQueue类的enqueueMessage()
boolean enqueueMessage(Message msg, long when) {
        //1
        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) {
            //如果调用了Looper#quit()或Looper#quitSafely(),会结束轮询,并释放资源
            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;
    }

在上面的代码注释1处,首先判断msg.target是否为null,根据Handler中的enqueueMessage()方法,可以发现msg.target是Message 内的一个Handler类变量。然后判断消息轮询是否结束,如果没有,则加入消息队列。到此,消息的添加就完毕了。

3、Looper分析

首先,Looper的创建

public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }


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");
        }
        //1
        sThreadLocal.set(new Looper(quitAllowed));
    }

prepareMainLooper()是在主线程创建Looper时调用的,最终也是调用了prepare()。在上面代码的注释1处,sThreadLocal是ThreadLocal的一个实例对象。sThreadLocal内部以当前线程作为key,创建的Looper实例作为value。主要在ThreadLocal的内部类ThreadLocalMap中实现。这样使得每个线程都有一个独立的Looper实例副本。

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 (;;) {
            //1
            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 {
                //2
                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利用for(;;)进入了无限循环。调用MessageQueue 中next()方法,会向MessageQueue 中取出消息,如果没有消息存在,next()会处于阻塞状态(这里是由底层实现的,调用了本地方法nativePollOnce()),当有消息返回时,会走到注释2处,调用Handler的dispatchMessage()进行分发消息。

public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

handleCallback()是在调用Handler#post(Runnable run)或者是设置了msg.callback时回调的。最后回调了 handleMessage()。

完篇~

你可能感兴趣的:(Android中的Handler消息机制)