美文网首页
Android个人对Handler机制的理解

Android个人对Handler机制的理解

作者: Preupen | 来源:发表于2018-12-06 11:28 被阅读0次

    一.系统为什么不允许子线程访问UI线程:

    这是因为UI线程里面的控件都是非线程安全的,如果在多线程并发访问可能会导致UI控件处于不可预期的状态。那么为什么不给控件访问加上锁呢?首先,加锁之后会导致访问逻辑变得复杂,其次锁机制会降低UI访问的效率,因为锁机制会阻塞某些线程的执行。

    二.消息机制的几个重要对象:

    Handler 发送和接收消息
    Looper 用于轮询消息队列,一个线程只能有一个Looper
    Message 消息实体
    MessageQueue 消息队列,存放消息实体的载体

    三.创建Looper

    在ActivityThread中的main方法中为我们prepare了

    public static void main(String[] args) {
            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
            //其他代码省略...
            Looper.prepareMainLooper(); //初始化Looper以及MessageQueue
    
            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.prepareMainLooper();

     public static void prepareMainLooper() {
            prepare(false);//消息队列不可以quit
            synchronized (Looper.class) {
                if (sMainLooper != null) {
                    throw new IllegalStateException("The main Looper has already been prepared.");
                }
                sMainLooper = myLooper();
            }
        }
    

    prepare有两个重载的方法,主要看 prepare(boolean quitAllowed) quitAllowed的作用是在创建MessageQueue时标识消息队列是否可以销毁, 主线程不可被销毁 下面有介绍

      public static void prepare() {
            prepare(true);//消息队列可以quit
        }
        //quitAllowed 主要
        private static void prepare(boolean quitAllowed) {
            if (sThreadLocal.get() != null) {//不为空表示当前线程已经创建了Looper
                throw new RuntimeException("Only one Looper may be created per thread");
                //每个线程只能创建一个Looper
            }
            sThreadLocal.set(new Looper(quitAllowed));//创建Looper并设置给sThreadLocal,这样get的时候就不会为null了
        }
    

    创建MessageQueue以及Looper与当前线程的绑定

     private Looper(boolean quitAllowed) {
            mQueue = new MessageQueue(quitAllowed);//创建了MessageQueue
            mThread = Thread.currentThread(); //当前线程的绑定
       }
    

    MessageQueue的构造方法

    MessageQueue(boolean quitAllowed) {
     //mQuitAllowed决定队列是否可以销毁 主线程的队列不可以被销毁需要传入false, 在MessageQueue的quit()方法就不贴源码了
            mQuitAllowed = quitAllowed;
            mPtr = nativeInit();
        }
    

    Looper.loop()
    同时是在main方法中 Looper.prepareMainLooper() 后Looper.loop(); 开始轮询

    public static void loop() {
            final Looper me = myLooper();//里面调用了sThreadLocal.get()获得刚才创建的Looper对象
            if (me == null) {
                throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
            }//如果Looper为空则会抛出异常
            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) {
                    //由于刚创建MessageQueue就开始轮询,队列里是没有消息的,等到Handler sendMessage enqueueMessage后
                    //队列里才有消息
                    // 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);//msg.target就是绑定的Handler,详见后面Message的部分,Handler开始
                //后面代码省略.....
    
                msg.recycleUnchecked();
            }
        }
    

    四.创建Handler

    最常见的创建handler

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

    在内部调用 this(null, false);

    public Handler(Callback callback, boolean async) {
            //前面省略
            mLooper = Looper.myLooper();//获取Looper,**注意不是创建Looper**!
            if (mLooper == null) {
                throw new RuntimeException(
                    "Can't create handler inside thread that has not called Looper.prepare()");
            }
            mQueue = mLooper.mQueue;//获得消息队列MessageQueue
            mCallback = callback; //初始化了回调接口
            mAsynchronous = async;
        }
    

    Looper.myLooper();

     //这是Handler中定义的ThreadLocal  ThreadLocal主要解多线程并发的问题
     // sThreadLocal.get() will return null unless you've called prepare().
     static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
     public static @Nullable Looper myLooper() {
            return sThreadLocal.get();
        }
    

    五.Handler消息机制整个流程

    1.handler内部与Looper关联,handler->Looper->MessageQueue,handler发送消息就是向MessageQueue队列发送消息。
    2.Looper通过Looper.loop()不断循环的方法并把消息(通过先进先出的顺序)通过dispatchMessage方法回传给handler自己。

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {//callback在message的构造方法中初始化或者使用handler.post(Runnable)时候才不为空
            handleCallback(msg);
        } else {
            if (mCallback != null) {//mCallback是一个Callback对象,通过无参的构造方法创建出来的handler,该属性为null,此段不执行
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);//最终执行handleMessage方法
        }
    }
     private static void handleCallback(Message message) {
            message.callback.run();
        }
    
    流程图

    注意:主线程中的Looper.loop()一直无限循环为什么不会造成ANR?

    也许讲到这里,很多人已经知道原因了吧!不过习惯使然,我还是要总结一下。主线程Looper从消息队列读取消息,当读完所有消息时,主线程阻塞。子线程往消息队列发送消息,并且往管道文件写数据,主线程即被唤醒,从管道文件读取数据,主线程被唤醒只是为了读取消息,当消息读取完毕,再次睡眠。因此loop的循环并不会对CPU性能有过多的消耗。

    相关文章

      网友评论

          本文标题:Android个人对Handler机制的理解

          本文链接:https://www.haomeiwen.com/subject/cqpncqtx.html