Handler只看这一篇就够了

误区

经常有人会这样理解

  • Android的消息机制就是Handler
  • Handler就是用来更新UI的

但实际上,正确的理解是

  • Android消息机制主要指Handler的运行机制,我们大部分的开发中只需要和Handler打交道就可以了,但Handler的底层需要MessageQueue和Looper的支撑。
  • Handler并不是专门用于更新UI的,它只是常被开发者用来更新UI。Handler的实际作用是可以轻松的将一个任务切换到Handler所在的线程中去执行。

理解Handler和UI的关系

下面将通过问答的方式来回答我们在开发过程中常遇到的一些问题,让大家更好的理解Handler

为什么只能在主线程中访问UI?

最直接的原因是,Android在更新UI时,在ViewRootImpl的checkThread方法中做了以下判断

void checkThread() {
        if (mThread != Thread.currentThread()) {
            throw new CalledFromWrongThreadException(
                    "Only the original thread that created a view hierarchy can touch its views.");
        }
    }

如果当前线程不是主线程,那么它更新UI时会抛出异常。

为什么需要做checkThread这个判断呢?

那是因为Android中的UI访问不是线程安全的,如果不做这个判断,那么每个线程都可以访问UI。这就会导致在子线程并发访问UI的过程中可能会出现各种各样意想不到的问题。

为什么不把UI的访问做成线程安全呢?

主要有一下几个原因:

  1. 做线线程安全意味着需要在代码中添加大量的锁处理,这个会增加很大的开发工作;
  2. UI中加锁会导致界面刷新变慢,甚至卡顿,这个对用户的体验来说影响很大(笔者觉得这个是主要原因);
  3. Android的消息机制已经很完善了,而且对用户来说Handler的使用也很简单。

Handler机制源码分析

Handler消息机制概述图

Handler消息机制

创建Handler

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Handler handler = new Handler();
        handler.sendMessage(Message.obtain());
    }
}

Handler有多种构造函数,但查看源码可以知道,不管哪种构造方式,最终真正都是调用了以下两种构造方式中的一种

使用默认Looper的方式

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

传入Looper的方式

    public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

	mLooper = Looper.myLooper();
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread that has not called Looper.prepare()");
    }

这段代码我们可以看出,如果不传入Looper参数,那么当前创建Handler的线程就必须含有Looper(关于Looper.myLooper();获取到的为什么是本线程的Looper,请查看文章,原理是使用了ThreadLocal),或者提前调用**Looper.prepare()**在当前线程创建Looper,否则会抛出异常。

Looper的prepare方法

	static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    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));
    }
  • 从上面我们可以看到,prepare方法为当前线程创建了Looper,而且一个线程中最多只会有一个Looper;
  • 还有一点需要注意的是,我们再onCreate方法中创建Handler时没有调用Looper.prepare那么为什么没有抛出异常呢?这是因为onCreate运行在主线程中,主线程在ActivityThread的main函数中为我们创建了Looper

主线程在ActivityThread的main方法中创建了Looper

public static void main(String[] args) {
        SamplingProfilerIntegration.start();

        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        // Set the reporter for event logging in libcore
        EventLogger.setReporter(new EventLoggingReporter());

        Security.addProvider(new AndroidKeyStoreProvider());

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");

        Looper.prepareMainLooper();

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

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

        AsyncTask.init();

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

        Looper.loop();

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

我们查看Looper.prepareMainLooper();方法

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

发现其实它也是调用了prepare方法,只是传入了不能停止Looper的参数,因为Looper一旦停止,程序就无法处理消息了,也就会抛出**throw new RuntimeException(“Main thread loop unexpectedly exited”);**异常

使用Handler发送消息

发送消息

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Handler handler = new Handler();
        handler.sendMessage(Message.obtain());
    }
}

进入sendMessage方法

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

进入sendMessageDelayed方法

public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
  • 可以发现,不管调用sendMessage还是sendMessageDelayed,最后都是调用了sendMessageAtTime方法

最后进入sendMessageAtTime方法

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

这个时候我们可以看到Android消息机制的另一个重要组成-MessageQueue了,看到这里时,我们发现这个MessageQueue并不是新生成的,而是被赋值的,我们看以下mQueue是怎么创建的。

MessageQueue的创建

在Handler的构造函数中被赋值

眼尖的同学会发现,mQueue其实是在Handler的构造函数中被赋值的

	public Handler(Callback callback, boolean async) {
        ...
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }
	public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

在Looper的构造函数中创建

现在,我们发现,mQueue原来来自创建Handler时使用的Looper,接下来我们看一下Looper时怎么创建MessageQueue的

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

查看源码我们可以发现,mQueue是在初始化Looper的时候创建的

因为Looper的构造函数是私有的,前面我们又发现一个线程中Looper最多只能有一个,所以我们得到一个很重要的结论

  • Handler:Looper:MessageQueue的数量关系是n:1:1
  • 即每个Looper中肯定有且只有一个MessageQueue,但是可以使用这个Looper创建多个Handler,使用这个Looper创建的Handler发送的消息,都将发送到该MessageQueue,再由该Looper进行处理。

接下来我们回到sendMessageAtTime方法

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方法

	private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
  • 这里我们需要主要**msg.target = this;**语句,这里是把当前Handler实例的引用赋值给了msg.target,这个在后面Looper处理MessageQueue的时候会用到;

接着我们查看MessageQueue的enqueueMessage方法

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("MessageQueue", 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;
    }
  • 通过上述的代码我们可以知道,新的Message会和MessageQueue中原有的Message队列从队列头开始比较,当when比在message队列中的message的when小的时候,插入新的message
  • 看到这里大家可能就会有疑问了,message已经写入MessageQueue了,那么Looper什么时候处理,在哪里处理Message呢?

Looper对消息的处理

loop方法

回过头来看ActivityThread中的main方法:

	public static void main(String[] args) {
        ...
        Looper.prepareMainLooper();

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

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

        AsyncTask.init();

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

        Looper.loop();

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

我们发现调用了prepareMainLooper方法后,Looper还调用了loop方法

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

去除这段代码中的安全和日志代码,我们可以得到下面的方法:

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

我们现在来讲解其中的关键点:

  • myLooper() 是使用ThreadLocal来获取本线程的Looper,没有Looper的线程调用该方法会抛出异常;
  • for(; ; ) 说明这个线程开始执行loop之后,就会不停的获取和处理消息,不会再做其它操作;
  • queue.next() 用来获取新消息用于处理;
  • msg.target.dispatchMessage() 用来处理新的消息;
    接下来我们重点讲以下消息的获取和处理

Looper获取Message

我们来看看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 (false) Log.v("MessageQueue", "Returning message: " + msg);
                        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("MessageQueue", "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;
        }
    }

上面的代码比较长,但核心的流程还是比较清晰的:

  1. 判断当前时间是否已经到了message需要处理的时间;
  2. 如果不是,那么记录下这个时间差,在这个时间差之后唤醒当前线程;
  3. 如果是,那么返回这个Message并出栈;

Looper处理Message

Looper处理Message调用了msg.target.dispatchMessage()
首先,前面我们说过,发送Message的时候,对msg.target赋值了当前Handler的实例引用,所以,当从线程A切到线程B执行Message处理时,Handler实例还是同一个。
接下来我们看看Handler的dispatchMessage;

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

可以发现,这里由三种消息的处理优先级

  1. Message中的Callback函数,优先级最高;
  2. 其次是mCallback引用,这是创建Handler实例时的可以传入的参数;
  3. 最后是Handler自带的handleMessage函数
    这意味着,如果这几种消息同时存在,那么Message中带的callback函数会被最先调用。

流程总结

流程总结图

Handler消息机制

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值