Handler

作者: lipy_ | 来源:发表于2017-04-26 17:17 被阅读0次

    Handler

    Android 异步消息处理机制 ,Handle机制其实也为我们提供了异步消息处理机制代码的参考。

    由于Android系统规定主线程不能被阻塞,所以耗时操作必须放在子线程中进行。但是子线程中又不能访问UI。

    Handler解决了在子线程中无法访问UI的矛盾。

    使用

    public void onClick(View v){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //拿到Message对象
                    Message msg = Message.obtain();
                    msg.arg1 = 1;
                    mHandler.sendMessage(msg);
                }
            }) .start();
        }
    
      private Handler mHandler =  new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //更新ui
            TextView.setText("msg = " + msg.arg1);
        }
    };
    

    实现消息驱动有几个要素:

    • 消息的表示:Message
    • 消息队列:MessageQueue
    • 消息循环,用于循环取出消息进行处理:Looper
    • 消息处理,消息循环从消息队列中取出消息后要对消息进行处理:Handler

    源码分析

    使用Handler之前,我们都是通过new Handler()初始化一个实例,同时会获取Looper和messageQueue的实例。

     public Handler(Callback callback, boolean async) {
            if (FIND_POTENTIAL_LEAKS) {
                //检测扩展此Handler类并且不是静态的匿名,本地或成员类。 这些类可能会产生泄漏。
                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());
                }
            }
    
            //默认将关联当前线程的looper
            mLooper = Looper.myLooper();
            if (mLooper == null) {
                throw new RuntimeException(
                    "Can't create handler inside thread that has not called Looper.prepare()");
            }
            //直接把关联looper的MQ作为自己的MQ,因此它的消息将发送到关联looper的MQ上
            mQueue = mLooper.mQueue;
            mCallback = callback;
            mAsynchronous = async;
        }
    

    Handler的send或者post类方法被调用时,最终会调用MessageQueue的enqueueMessage方法,将消息放入消息队列中。(post(Runnable r)中的Runnable对象会被封装成message对象)

        //发送消息
        public final boolean sendMessage(Message msg){
            return sendMessageDelayed(msg, 0);
        }
        
        //发送消息
        public final boolean sendMessageDelayed(Message msg, long delayMillis){
            if (delayMillis < 0) {
                delayMillis = 0;
            }
            return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
        }
        
        //最终都是调用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);
        }
        
        
        private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
            msg.target = this;//meg.target赋值为当前handler
            if (mAsynchronous) {
                msg.setAsynchronous(true);
            }
            //调用enqueueMessage()将Message送到MessageQueue中去,该MessageQueue的实例是looper在初始化的时候创建的
            return queue.enqueueMessage(msg, uptimeMillis);
        }
    
    

    当Looper发现有新消息来时,就会处理这个消息(Android 在进程的入口函数 ActivityThread.main()方法中,会调用 Looper.prepareMainLooper(), 为应用的主线程创建Looper,然后调用Looper.loop()就启动了进程的消息循环。所以我们在activity中创建的Handler默认是运行在ui线程中的,可以直接更新ui。我们也可以在自线程中去调用Looper.prepare()方法去创建该线程的Looper)

    //
    public static final void prepare() {  
            //一个线程中只有一个Looper实例
            if (sThreadLocal.get() != null) {  
                throw new RuntimeException("Only one Looper may be created per thread");  
            }  
            sThreadLocal.set(new Looper(true));  
    }
    
    //轮询处理调用handler.
    public static void loop() {
            final Looper me = myLooper();//获取ThreadLocal中存储的Looper实例
            //需要先调用prepare()创建Looper实例
            if (me == null) {
                throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
            }
            final MessageQueue queue = me.mQueue;//获取该looper实例中的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.target 是handler中enqueueMessage()方法中msg.target = this赋值的handler实例
                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();
            }
        }
    
    

    looper轮询处理消息调用dispatchMessage()方法

     // 处理消息,该方法由looper调用
     public void dispatchMessage(Message msg) {
            // 如果message设置了callback,即runnable消息,处理callback!
            if (msg.callback != null) {
                handleCallback(msg);
            } else {
                // 如果handler本身设置了callback,则执行callback
                if (mCallback != null) {
                    if (mCallback.handleMessage(msg)) {
                        return;
                    }
                }
                //调用handleMessage()方法,内部是空实现,交给用户复写,处理消息。
                handleMessage(msg);
            }
        }
        
        
         // 处理runnable消息
        private final void handleCallback(Message message) {
            message.callback.run();  //直接调用run方法
        }
        // 由用户复写
        public void handleMessage(Message msg) {
        }
    

    Message
    在整个消息处理机制中,message封装了任务携带的信息和处理该任务的handler。

    1. 尽管Message有public的默认构造方法,但是推荐通过Message.obtain()来从消息池中获得空消息对象,以节省资源。
    2. 如果你的message只储存int信息,优先使用Message.arg1和Message.arg2来传递信息,这比用Bundle更省内存
    3. 擅用message.what来标识信息,以便用不同方式处理message。

    相关文章

      网友评论

          本文标题:Handler

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