如何正确的使用Handler,带你从源码上认识!

首先来看看平时使用Handler的一些习惯,通常我们在子线程中做了很多耗时操作,比如数据处理,网络请求等,在处理完后我们需要去更新UI,这个时候就发送一个消息到Handler,handler通过handleMessage(Message msg)处理:

    new Thread(new Runnable() {
            @Override
            public void run() {
                //耗时操作
                try {
                    Thread.sleep(10*1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //创建一个Message
                Message msg = Message.obtain();
                msg.what=0;
                mHandler.sendMessage(msg);
            }
        }).start();

上面的代码非常简单,就是子线程模拟耗时,然后发送一个消息,那么怎么接收和处理这个消息呢? 请继续往下看:

private  Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
          switch (msg.what){
              case 0:
                  //do something
                  break;
              case 1:
                 // do something
                  break;
              default:
                  //do something
                  break;
          }

        }
    };
好了,这就是Handler的基本用法。嗯?太啃爹了吧,尼玛这蜀中小儿都知道的东西,你竟然说从源码解析。
大兄弟你别慌,下面我们展示一些错误引出问题:
什么错误?在子线程中去创建一个Handler呢?直接动手:
new Thread(new Runnable() {
            @Override
            public void run() {
                mHandler1=new Handler();
            }
        }).start();

艹,怎么crash(崩溃)了?

这里写图片描述

什么意思?不能在没有调用Looper.perpare()的内部线程(子线程)创建Handler? 好吧!戳开Handler源码查看:

 public Handler(Callback callback, boolean async) {
     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;
    }

上面代码可以看到,在5行跑出了上面崩溃的异常,这个异常的原因就是mLooper对象为null引起的。 追随问题的原因去查看Looper.myLooper()为什么返回的是null

/**
* Return the Looper object associated with the current
* thread.  Returns
* null if the calling thread is not associated with a Looper.
*/
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }
  这个方法太简单了,就是直接去get一个Looper,这个方法给的注释说的很清楚,意思就是该方法返回一个和当前线程相关的Looper对象,如果没有相关的就返回null,看到return sThreadLocal.get()这一句,在继续查找,
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));
    }

这个方法可以看到,如果这个对象不为null会异常,没有就会new Looper(),也就是说这个方法在当前线程只能调用一次,如果调用一次以上就会异常,大家可以自己在代码中试一下。
所以上面报错的代码改为如下就可以了:

new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                mHandler1=new Handler();
            }
        }).start();

有人就要问了,嗯?怎么主线程不用调用Looper.prepare()不会异常呢?


这里写图片描述


我早就知道聪明的你一定会问,所以下面为你准备了大餐。
Android的真正入口在哪里呢,是不是onCreate()?答案当然是不正确的。真正的入口是ActivityThread类的main方法。

public static void main(String[] args) {  
    SamplingProfilerIntegration.start();  
    CloseGuard.setEnabled(false);  
    Environment.initForCurrentUser();  
    EventLogger.setReporter(new EventLoggingReporter());  
    Process.setArgV0("<pre-initialized>");  
    Looper.prepareMainLooper();  
    ActivityThread thread = new ActivityThread();  
    thread.attach(false);  
    if (sMainThreadHandler == null) {  
        sMainThreadHandler = thread.getHandler();  
    }  
    AsyncTask.init();  
    if (false) {  
        Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread"));  
    }  
    Looper.loop();  
    throw new RuntimeException("Main thread loop unexpectedly exited");  
} 

这里调用了Looper.prepareMainLooper()方法

/**
 * Initialize the current thread as a looper, marking it as an
 * application's main looper. The main looper for your application
 * is created by the Android environment, so you should never need
* to call this function yourself.  See also: {@link #prepare()}
*/
    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()这个里面就创建了Looper,
sMainLooper = myLooper()得到了Looper
在Looper中又创建了MessageQuene对象,这样就一个Looper对应唯一的MessageQuene。

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

以上就是整个Looper,Handler和MessageQueue创建的关系,可以说是剪不断理还乱的感觉。后面我还会在梳理一下。那么接下来看这个消息是怎么发送出去的,怎么保证了一对一的关系,不是这个Handler发送另外的Handler接收呢?
我们调用handler.sendMessxxxx最终都会回到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);
    }

传入的Message对象和uptimeMillis参数通过enqueueMessage方法进入消息队列


 private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

msg.target = this;这一句太关键了,给这个Message标记一个tager,这个this就是当前类的对象,这个方法是在Handler中的,所以这个this就是这个Handler,哪个handler发送,后面取出这个targer(handler)就形成了一一对应的关系,即使再多的消息在队列中也不会错乱。也就是说一个线程中可以有多个handler,却只有一个Looper和MessageQuene,同个handler多次发送消息在消息队列中进行时间排序,也会保证消息的顺序。


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(TAG, 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;
    }

这个进入消息队列的方法太多,部分代码也看不懂,不过我们只要知道它大致是干什么的就行了,该方法主要是通过时间给消息排序,这个时间当然就是我们刚才介绍的uptimeMillis参数。具体的操作方法就根据时间的顺序调用msg.next,从而为每一个消息指定它的下一个消息是什么。


public static final void loop() {  
    Looper me = myLooper();  
    MessageQueue queue = me.mQueue;  
    while (true) {  
        Message msg = queue.next(); // might block  
        if (msg != null) {  
            if (msg.target == null) {  
                return;  
            }  
            if (me.mLogging!= null) me.mLogging.println(  
                    ">>>>> Dispatching to " + msg.target + " "  
                    + msg.callback + ": " + msg.what  
                    );  
            msg.target.dispatchMessage(msg);  
            if (me.mLogging!= null) me.mLogging.println(  
                    "<<<<< Finished to    " + msg.target + " "  
                    + msg.callback);  
            msg.recycle();  
        }  
    }  
}  

这个loop里面是一个死循环,next()方法不断的从队列中取出消息, msg.target.dispatchMessage(msg); 等价于 handler.dispatchMessage(msg);


/**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
           handleMessage
        }
    }

如果没有callback就回到了handleMessage,否则调用handleCallback(msg);


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

handleCallback调用了callback.run()里面的代码。

接下来我们梳理一下:
Message
Handler
Looper
MessageQuene
在子线程中创建Handler的时候要手动调用Looper.prepare(),这个prepare()里面又创建了MessageQueue,这样一个Looper对应一个MessageQueue。
Handler调用sendMessxxx(Message msg)会给这个参数标记一个target,取出这个target调用handerMessage(Message msg)。

看完了请回到问题:
1.Handler、Looper、MessageQueue何时建立的相互关系?
2.主线程为什么不需要调用Looper.prepare(),而子线程不掉就会异常?
3.在同一线程中,Looper和MessageQueue是怎样的数量对应关系,与Handler又是怎样的数量对应关系?
4.在子线程中调用handler.sendMessagexx... 后面又是怎么回到主线程的?
回答完以上问题说明你才真正懂了handler的消息机制!
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值