Handler异步更新Ui的机制

转载请说明来自;http://blog.csdn.net/super_kingking/article/details/51317789
我们在开发过程中都知道,工作线程做耗时操作,然后在主线程中(UI线程)更新UI。在主线程中创建

Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //更新ui的操作
            //do something...
        } };,

    发送message 
    new Thread(new Runnable() {
        @Override
        public void run() {
            Message message = new Message();
            message.arg1 = 1;
            message.obj = "发送message到主线程";
            handler.sendMessage(message);
        }
    }).start();
   在重写handleMessage的方法中更新ui,但是大家知道其中的原理吗?

下面我们带着问题来看一下。

首先我们来看一下,一个最标准的异步消息处理线程的写法应该是这样:

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

这里为什么要添加Looper.prepare()和Looper.loop(); ,这俩个方法是什么作用呢,如果我们不写会怎么样?
下面去掉这俩个方法

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new Thread(new Runnable() {
            @Override
            public void run() {
               Handler handler = new Handler(){
                   @Override
                   public void handleMessage(Message msg) {
                       super.handleMessage(msg);
                   }
               };
            }
        }).start();
    }
}
运行结果报错java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

查看一下handler的无参数构造方法

 public Handler(boolean async) {
        this(null, async);
    }

调用的是下面这个构造函数
  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为空则会抛出这个”Can’t create handler inside thread that has not called Looper.prepare()”异常报错,在什么情况下mLooper会为空呢,我们下面打开Looper.myLooper()方法,

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
 public static Looper myLooper() {
        return sThreadLocal.get();
    }

原来是从sThreadLocal 里面获取的,如果sThreadLocal 里面有Looper则去获取,如果没有则返回为空。那什么时候在sThreadLocal 里面赋值才不会为空呢,那我们来看一下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));
    }

原来是在这里,如果if (sThreadLocal.get() != null) 则会报错,如果没有的话就会在sThreadLocal中new一个新的Looper存到sThreadLocal中。在线程当中尤其只有一个Looper存在,否则会报throw new RuntimeException(“Only one Looper may be created per thread”);这里我们明白为什么要调用Looper.prepare()方法了吧。

下面问题来了,为什么我们在主线程中创建Handler实例时并没有报错。

public class MainActivity extends AppCompatActivity {

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

原来是主线程中有 Looper.prepareMainLooper()和 Looper.loop(); 我查看一下 Looper.prepareMainLooper()里面是什么

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

原来是存在prepare(false)的,这里就明白了在主线程中不要添加Looper.prepare()和Looper.Loop()方法的原因了,默认已经是添加过了的,所以不需要我们重新添加了,但是在子线程中创建Handler是需要我们手动添加这俩个方法的。

下面我们来看一下handler发送消息message。

在message创建的时候有new实例message对象和Message.obtain();俩种方法,

下面我来查看一下这俩种方法获取Message的区别。
new Message()我就不用说了,通过构造函数创建一个message实例。重点看一下obtain(),贴出源码

private static Message sPool;
// sometimes we store linked lists of these things
    /*package*/ 
 Message next;
............................
 public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

通过源码可以看出如果sPool如果存在的话,就赋给m,然后返回,如果没有则new Message()创建一个。重复利用message,避免更多的内存开销,所以我们在创建message的时候可以调用obtain()。

下面查看源码来看一下对应关系

 private static void prepare(boolean quitAllowed) {
 //如果sThreadLocal中存在Looper则报错
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //重新创建一个Looper
        sThreadLocal.set(new Looper(quitAllowed));
    }

由此可以看出在创建子线程的时候,Looper.prepare()方法中显示只能有一个Looper对象存在,那为什么一个Looper对象只能有一个MessageQueue 呢?
进入Looper的构造函数

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

在Looper的构造方法中创建了MessageQueue实例,因此一个Looper有且对应一个MessageQueue。

 private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
 //这里的target指的是Handler,enqueueMessage是Handler的方法
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

第三个参数uptimeMillis参数则表示发送消息的时间,它的值等于开机到当前时间的毫秒数再加上延迟时间。

最后进入queue.enqueueMessage(msg, uptimeMillis)方法中一探究竟,这里是入队的核心程序。

 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("MessageQueue", 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入队的核心代码,enqueueMessage并没有一个集合用来存在入队的message,而是通过一个mMessages表示待处理的message消息。入队的时间uptimeMillis参数,根据时间的顺序调用msg.next,指定它的下一个消息是那个message。

那入队ok了,出队在哪里呢,还有一个方法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();
        }
    }

首先调用myLooper()方法拿到Looer实例me,调用Looper里面的MessageQueue,进入for循环,便利消息消息对列,queue.next()方法获取Message,请注意27行,这里是处理消息的关键,首先Message的形参msg的target是什么,回顾我们之前写到的

 private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
 //这里的target指的是Handler,enqueueMessage是Handler的方法
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

看到了吧,这里的target其实就是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);
        }
    }

第5行,如果mCallback不为空的话则调用则调用mCallback的handleMessage()方法,mCallback是从哪里来的呢?在Handler的俩个构造函数里面,这里我就不贴出来源码了。如果按照我们前面所写的代码来说,我们初始化handler的时候并没有在构造函数里面传入mCallback,所以mCallback一定为空,然后就会去调用重写的handleMessage(msg),这里终于理清楚我们调用handler发送消息,最终在重写的handleMessage(msg)中处理。

那什么时候出现在msg.callback != null呢,现在去想一下什么时候出现这种情况呢?我来看一下其它在子线程中发送消息在UI线程中更新ui的方法
1.handler.post(Runnable r) 2.view.post(Runnable action) 3.runOnUiThread(Runnable action)

下面我们查看一下handler.post(Runnable r)源码

 public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }
    private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

handler.post方法里面跟我们之前调用的handler.sendmessage()方法体其实是一样的,我们观察getPostMessage(Runnable r)方法,其实就是把Runnable方法转换成了Message,m.callback = r,这就对应上面的 if (msg.callback != null),原来是这种情况话才会出现msg.callback != null,那如果不等于空的话,则调用handleCallback(msg),handleCallback(msg)的方法是怎么处理的Message呢?

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

非常简单,就是直接利用Message对象的变量Runnable传入的run方法。

再来看看 2.view.post(Runnable action) 方法 和 3.runOnUiThread(Runnable action) 我们直接贴源码,原理其实都是一样的

view.post(Runnable action)

  public boolean post(Runnable action) {
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            return attachInfo.mHandler.post(action);
        }
        // Assume that post will succeed later
        ViewRootImpl.getRunQueue().post(action);
        return true;
    }

runOnUiThread(Runnable action)

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

其实最后都是调用的handler.post(Runnable r)方法。

总结,最终的message都是在dispatchMessage(Message msg)方法中处理,在其中存在俩种情况,
1是handler.post()的情况,将runnable转化成Message,这种情况下msg.callback != null,最终直接调用的run().
2. 就是handler.sendMessage(),如果mCallback为空的话,就走我们所的重写handleMessage()方法。
无论哪种在子线程中发送消息更新UI的方式,其实到最后原理都是一样的,最终还是在Handler的方法中实现操作Message。

如果有什么问题,希望各位大神多多指教。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值