Android 异步消息处理机制 Handler、Looper、Message、MessageQueue之藕断丝连

1 篇文章 0 订阅
1 篇文章 0 订阅

本文参考于郭霖- Android异步消息处理机制完全解析,带你从源码的角度彻底理解 鸿洋_Android 异步消息处理机制 让你深入理解 Looper、Handler、Message三者关系
并试图自己重新总结、加固知识,不能算是百分百原创(也顺便练习下markdown)。
本文从会源码角度分析几者的关联(不要怕,源码高大上,我们只需先理解需要的部分即可)。

带着几个疑问学习

  • 为什么要使用Handler?
  • 为什么在Activity中直接new Handler()一个匿名内部类就直接能sendMessage和handleMessage处理了呢?那么我在子thread中可以吗?
  • 我们有时会new Handler()很多次,有什么影响?

Handler的使用

如果我们在子线程中操作一个UI控件,如:

    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
    }

    public void testHandler(View view) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                button.setText("踩你!");
            }
        };
        thread.start();
    }

如果你运行的话,不好意思,迎接你的是: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.当然此刻程序已经boom掉了^_^

看到了吧,android 的UI操作只能在original thread中操作(也就是UI线程)。所以也就知道了Handler最常使用的地方,当然也有其他的方式操作ui,只不过这个最常用、最简单。

Handler创建

我们分别在UI线程和子线程中new Handler(),来看看效果。

public class MainActivity extends AppCompatActivity {
    private Handler uiHandler;
    private Handler sHandler;

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

    /**
     * button 的点击事件
     *
     * @param view
     */
    public void testHandler(View view) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                sHandler = new Handler();
            }
        };
        thread.start();
    }

}

运行完说明UI线程中的Handler已经创建完毕。当你点击按钮时,会创建子thread中的Handler,系统又给你了个“boom”:java.lang.RuntimeException: Can’t create handler inside thread that has not called Looper.prepare()
运行的时候Android studio 会把错误定位到第21 行 sHandler = new Handler();那么我们就去Handler里面看个究竟,代码片段如下(API Level 25的源码):

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

还没到地方,继续游…

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

哎呀,终于到岛上了,来来来,上岸歇一会儿。

请看第13、14 行,错误就是从这里抛出的。if (mLooper == null) 会出现这个错误,那么我们再努力一把,去那个礁上看看。

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

进入Looper

来到Looper的Looper.myLooper()方法,会看到只是从sThreadLocal中get()得到一个looper实例,那么这个实例是什么时候创建的呢。
sThreadLocal是类Looper中声明的成员变量“static final ThreadLocal sThreadLocal = new ThreadLocal();”ThreadLocal是用来创建线程局部变量的类,ThreadLocal创建的变量只能被当前线程访问,其他线程则无法访问和修改。可参考理解Java中的ThreadLocal

不要忘了我们之前被迫双手接到的“Can’t create handler inside thread that has not called Looper.prepare()”错误,既然说没有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));
    }

哈哈,给逮到了吧^_^
2、3 行表示一个Thread中只能有一个Looper,prepare方法看来不能多次执行喽!
5 行就是new了一个looper添加到了sThreadLocal,这个知道为什么前面Looper.myLooper()为null了。

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

没看到主线程prepare()啊

那么我们就有疑问了,在子线程中我们需要Looper.prepare(),可是主线程中我们也没有调用啊,为什么不报错呢?!哈哈,Androd对于每个程序都有一个ActivityThread的main入口,那么我们去看看(下面临时找到的是5.1.1的源码):

public static void More ...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();
    }

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

    Looper.loop();

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

找到了吧,第22 行,其实还是跟子线程的prepare没有什么不一样,最终调用了prepare(boolean b)。如下

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

由于程序开始时就已经在UI线程中Looper.prepareMainLooper()过了,所以我们在Activity中new Handler(),自然也不会报错了。

Handler.sendMessage的去处

话说往刚才5.1.1的ActivityThread的源码往下瞟到了第36行,Looper.loop();这是什么鬼,这就是我们循环获取Handler发送的Message的地方。
先看sendMessage,看源码的话你会发现,不管sendXXX什么,除了sendMessageAtFrontOfQueue之外都会最终走到sendMessageAtTime,说白了,他们俩也是大差不差,我们来看sendMessageAtTime,uptimeMIllis是SystemClock.uptimeMillis() + delayMillis,SystemClock.uptimeMillis()表示从开机boot到现在的毫秒数(不计休眠的时间):

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

2 行的mQueue也是new Handler()的时候通过sThreadLocal.get()得到的,是new Looper时创建的Looper中的成员变量。来看第9 行enqueueMessage

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

好嘛还没到,去MessageQueue中(此处应注意msg.target = this,后面会用到)

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

总体的意思就是组合起来一个Message链条,使用.next()相连。20 -45 行就连接起来的方式。不是说了吗,MessageQueue就是存取Message的仓库,此方法是存。

Looper.loop()从MessageQueue中取Message

那么什么时候取呢,注意的话,在刚才5.1.1的ActivityThread的源码往下瞟到了第36 行,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 traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

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

2 行是获取此Thread已保存的Looper实例,在Looper.prepare()已生成。
6 行是获取此Thread中已生成的Looper实例中的mQueue,new Looper()中创建。
13 行到后面就是循环获取,被send进MessageQueue队列中的Message了。
14 行queue.next()起到阻塞的作用,当MessageQueue中没有message时触发。
请看32 行,msg.target之前已经说了,是在Handler的enqueueMessage中,msg.target = this,this当然就是Handler。msg.target.dispatchMessage(msg),继续在Handler中查看。

   /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

好了,一般都会走到第13 行,这不就是我们平常经常使用的回调嘛,哈哈哈^_^

        uiHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
            }
        };

看到了吧,这就是从开始new Handler(),到最后回调这里的handleMessage的整个过程。

官方标准Handler使用

一个最标准的异步消息处理线程的写法应该是这样的:

 class LooperThread extends Thread {
     public Handler mHandler;

     public void run() {
         Looper.prepare();

         mHandler = new Handler() {
             public void handleMessage(Message msg) {
                 // process incoming messages here
             }
         };

         Looper.loop();
     }
 }

这也是Android官方的东西,点进去Looper的最上面类介绍中就有。

几个常用的点

当然,平时经常用到的还有
1. Handler的post()方法
2. View的post()方法
3. Activity的runOnUiThread()方法

先看Handler的post()方法

    public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }

其中getPostMessage(r)的实际情况是

    private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

看到第3 行的m.callback = r;了吧,如果r不是null,就会走到上面dispatchMessage中的handleCallback(msg),也仅仅是回调了run()方法,其实此地的Runnable并没有用到它线程的东西,就是执行一个方法而已。

    private static void handleCallback(Message message) {
        message.callback.run();
    }

那么我们看view的post方法,第4

    public boolean post(Runnable action) {
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            return attachInfo.mHandler.post(action);
        }

        // Postpone the runnable until we know on which thread it needs to run.
        // Assume that the runnable will be successfully placed after attach.
        getRunQueue().post(action);
        return true;
    }

再看Activity中的runOnUiThread方法

    public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }

3、5 行,一切皆是如此。Activity中直接声明了final Handler mHandler = new Handler();也就是说runOnUiThread会根据被调用的位置,分别执行mHandler.post(action)或是action.run()。

回马枪

小结一下,
1. 使用Handler多数时候是为了在子线程中操作UI。
2. 在UI线程中不需要Looper.prepare()和Looper.loop(),因为从程序开始加载运行,就在ActivityThread自动执行了 Looper.prepareMainLooper()和Looper.loop()。
3. 一个Thread中,Looper实例只能有一个,当然mQueue也是一个,那么不管你new Handler了几次,都执行的一个Looper,只不过msg.target.dispatchMessage(msg)的msg.target还是发送message时候的Handler。

啥也不说了,上图:
Handler示意图

其他:
1. Android中为什么主线程不会因为Looper.loop()里的死循环卡死

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值