带你深入理解Android Handler机制

带你深入理解Android Handler机制


欢迎转载请注明来源

说到消息机制,我们一定会想到Handler,由于Android系统规定主线程不能阻塞超过5s,否则会出现”Application Not Responding”。也就是说,你不能在主线程中进行耗时操作(网络请求,数据库操作等),只能在子线程中进行。下面先来看一下在子线程中访问UI会出现什么情况。

  public void click(View v){
    new Thread(new Runnable() {
        @Override
        public void run() {
            mTextView.setText("2");
        }
    }) .start();
}

结果不出意外的报错:

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

在ViewRootImpl的checkThread()检查是否是主线程,如果不是抛异常。

那么这个时候怎么解决才能在更新UI呢?其实就是用Handler机制啦!

Handler

先来看一下如何改进代码,然后详细分析Handler机制。

   public void click(View v){
    new Thread(new Runnable() {
        @Override
        public void run() {
            //拿到Message对象
            Message msg = mHandler.obtainMessage();
            msg.arg1 = 2;
            mHandler.sendMessage(msg);
        }
    }) .start();
}

然后在handleMessage中更新UI

   private Handler mHandler =  new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        mTextView.setText(msg.arg1+"");
    }
};

这样就成功了。

仅仅知道怎么用那肯定是不够的,我们还需要知道其背后到底干了什么。

我们就从 mHandler.sendMessage(msg)开始说起吧。当我们调用sendMessage时候,其实最终调用的是sendMessageAtTime(msg,long)。此方法源码如下:

    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()将Message送到MessageQueue中去。那么MessageQueue是什么呢?顾名思义是消息队列,其实在我们创建Handler的时候,它需要与Looper作关联,Looper类有一个成员变量
MessageQueue mQueue,它就是消息队列。用来接收Handler发送Message。MessageQueue内部并不是用数组存储的,而是用链表的数据结构,方便添加和删除。

下面来看一下Looper.looper()源码,这个方法就是将Message交给Handler.handleMessage去完成的。

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

第3,4行:判断Looper对象是否为空,如果是空,抛出”No Looper; Looper.prepare() wasn’t called on this thread.”异常。换句话说,如果我们在子线程中创建Handler,并调用sendMessage()时候,由于没有Looper对象,就会抛此异常信息。我们可以通过Looper.prepare()将当前线程转为Looper线程。该源码会在下面分析。

主要看 for (;;)那段代码,它是个死循环,不断地执行next()方法,如果有新消息,就交给 msg.target.dispatchMessage(msg);这里msg.target其实就是Handler对象。那么下面我们看一下Handler.dispatchMessage(msg)到底干了什么。

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

其实看到这里就明白了,它调用的就是handleMessage(),所以我们就可以轻松的更新UI界面了!

那么mCallback.handleMessage(msg)是什么呢?

接下来我们看一下这个代码:

    private Handler mHandler =  new Handler(new Handler.Callback() {
    @Override
    public boolean handleMessage(Message msg) {
        Toast.makeText(getApplicationContext(),"1",Toast.LENGTH_SHORT).show();
        return false;
    }
}){
    @Override
    public void handleMessage(Message msg) {
        Toast.makeText(getApplicationContext(),"2",Toast.LENGTH_SHORT).show();
    }
};

注意:在第5行我return false,结果吐司展现1,展现完之后再展示2.
当return true时,结果吐司只展现1。这样我们就可以知道,这其实是用来拦截处理消息的。

刚刚提到Looper.prepare()可以将当前线程转为Looper线程。那看一下Looper.prepare()源码

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

通过抛出的那个异常我们可以发现一个Handler只能有一个Looper.而一个Looper内部维护者MessageQueue,当有消息时Looper从MessageQueue中取出消息交给Handler处理。这样它们之间就建立起关系了。

看一下源码中的这行代码 sThreadLocal.set(new Looper(quitAllowed)); 关于ThreadLocal可以看一下我的这篇文章

http://blog.csdn.net/qq_31609983/article/details/52094032

要想到Looper不断的从MessageQueue中取消息,就必须调用Looper.loop()来不断取消息.

在子线程中发送消息的完整代码如下:

    public void click(View v){
    final Handler handler =  new Handler();
    new Thread(new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            handler.sendMessage();
            Looper.loop();
        }
    }) .start();
}

注意 Looper.prepare(); handler.sendMessage();这二个方法顺序不能变,我们可以看一下Handler构造方法

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

注意这段代码 mLooper = Looper.myLooper();如果为空,抛异常,该异常意思是必须调用Looper.prepare().这就是说为什么顺序不能改变!

那么读者可能会问,我们在主线程创建Handler对象,并没有调用Looper.prepare()也出什么问题啊,的确是这样的,因为ActivityThread 的main()函数里面 Looper.prepareMainLooper();已经自动帮我们创建好了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();
    }
}

注意sMainLooper = myLooper();看一下myLooper()方法:

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

讲了这么多,估计对于小白来说有点晕了。哈哈。那么接下来我盗用一张hyman老师的一张图分析Handler,MessageQueue,Looper之间的关系吧。。。

0160904160222603)

一天,老板正在和员工开会,员工想上厕所,出于礼貌,对老板说我要去上厕所(sendMessage 到 MessageQueue中) 老板思考了一会儿,回复到”你去吧”(Looper.loop()) , 最后员工去WC了(handleMessage) ,从询问到最后WC都是员工做的事,这就是它们之间的关系了。。。哈哈哈。

其实Handler发送消息有多种方式

  • msg.sendToTarget();
  • mHandler.sendMessageAtFrontOfQueue();
  • mHandler.sendEmptyMessage()
  • mHandler.sendEmptyMessageDelayed()
  • mHandler.post()
  • mHandler.postDelayed()

虽然有多种方法,但本质都是通过Handler.handleMessage()实现的。

还有几个这里就不一一列举了,有兴趣的读者可以去Android官网吧。。。

声明

感谢《Android开发艺术探索》,感谢慕课网视频,感谢郭神。
我来附一下链接吧,感兴趣的话去看一下吧。。。

视频:

http://www.imooc.com/learn/267

郭神博客:

http://blog.csdn.net/guolin_blog/article/details/9991569

最后:这是笔者第一次写分析源码的文章,(估计也是最后一次了吧。。。哈哈哈。。),写的不好,比较杂乱,还请读者多多包涵。写着写着就过了24点了,即将迎来大三,希望用这篇文章来为准大三生活开个好头吧!祝大家生活愉快!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值