Android学习笔记:Android消息处理机制之Handler介绍

来源:互联网 发布:js removeattribute 编辑:程序博客网 时间:2024/04/29 22:18

  Handler介绍:
  1,Handler是什么:Handler是Android系统用来更新主UI界面的一种异步操作机制,也是Android中用来接收消息,处理消息的一种消息处理机制 。
  2,在Android中为什么要使用Handler:Android中主线程(UI线程)不能执行耗时操作,也不能在子线程中直接更新UI信息,为了实现主线程与子线程的信息交互, 为了解决交互问题,Android在时候,就封装了Handler消息传递处理机制,如果不使用Handler机制,程序就可能报异常。  Android设计Handler机制最根本的目的就是解决多线程并发问题:如果我们在同一界面(Activity)中有多个线程去更新UI,如果没有加锁机制,则会导致界面更新紊乱的问题?如果我们通过加锁机制来处理,那么程序的性能就会大打折扣。而通过Handler机制,我们不用去关心多线程问题,Ui更新操作我们通过Handler消息去处理。

 3, Handler原理(Handler,Looper,MessageQueue关系):

   Handler主要是封装消息的发送及处理。

  Looper:在Looper内部包含一个消息队列(MessageQueue),所有的Handler发送的消息都会经由这个消息队列处理Looper.loop()方法,其实就是一个死循环,不断地从消息队列(MessageQueue)  中获取消息,如果有消息就处理消息,没有消息则阻塞。

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

 所以说MessageQueue作为消息队列,主要是装载消息和处理消息。
 Handler处理消息是跟Looper进行关联的,在Handler内部可以找到Looper及Looper中的MessageQueue,Handler发送消息其实就是把消息发送到对应Looper中MessageQueue中。
总结而言:Handler发送消息,Looper负责消息的接收存储到MessageQueue中,最终会把消息传递给Handler,由Handler来处理(public void handleMessage(android.os.Message msg))消息。
 
0 0