Android源码分析-异步消息机制

时间:2022-11-15 08:07:00
 异步消息机制源码分析:
三大主角:Handler,Looper,Message.
我们知道安卓的UI线程就是主线程,除了不能再主线程做耗时操作外,还不能在子线程中更新UI,但是在子线程中更新UI是我们最常见的一种需求了,那怎么办呢,大家肯定就会想到下面的写法了:
        mHandler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    //更新你的UI
                    case UPDATE:
                        break;
                    default:
                        break;
                }
            }
        };
      或者这样
       mHandler=new Handler(new Handler.Callback() {//这里直接传入的是Handler的一个内部接口的实例.
            @Override
            public boolean handleMessage(Message msg) {
                return false;
            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                //其他耗时操作
                Message msg=Message.obtain();
                msg.what=UPDATE;
                mHandler.sendMessage(msg);

                /*mHandler.sendEmptyMessage(UPDATE);
                mHandler.post(null);
                mHandler.postAtFrontOfQueue(null);
                mHandler.postAtTime(null,null,0);
                mHandler.postDelayed(null,0);
                mHandler.sendMessageAtFrontOfQueue(null);
                mHandler.sendMessageAtTime(null,0);
                mHandler.sendEmptyMessageDelayed(UPDATE,0)*/
            }
        });

这样我们就可以在线程中通过这种方式来实现通知UI线程来更新UI了,是不是很方便,那么大家有去想过它是怎么运作的吗?下面我就来带领大家从源码的角度来理解异步消息的运作原理。

老规矩从我们的使用方法来分析:
       从创建Handler开始,分析Handler的构造函数开始,首先不管我们怎么创建Handler最终会调用这个构造函数:
       
    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 = Looper.myLooper();//创建了一个Looper对象,他是干嘛的的呢,我们先不去管,接着看下去,  
     myLooper的源码如下
     
    public static Looper myLooper() {
        return sThreadLocal.get();//这个sThreadLocal又是什么鬼呢?
    } 
    
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();//这是个什么玩意呢,引用别人说的一句话就是"ThreadLocal的应用场合,我觉得最适合的是按线程多实例(每个线程对应一个实例)的对象的访问,并且这个对象很多地方都要用到";意思就是说我们的这个Looper对象是跟我们的线程绑定好了的,不管你其他线程是不是也有这个对象,反正我只用自己的,别个线程相对于我来说也是独立的使用它所持有的对象,互不干扰。
    
    竟然是通过get方法得到的,那么肯定有set方法,我们看Looper 中的sThreadLocal的set方法在哪里调用的:

    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));
    }
//如果sThreadLocal没有存储Looper对象直接调用Looper的一个参数的构造函数,并且这个构造函数是私有的,外界不可以直接创建,这样进一步说明了一个线程只可以绑定一个Looper对象
   那我们来看看这个构造函数做了什么事情:
       private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);//消息队列
        mThread = Thread.currentThread();
    }
    
   创建了一个消息队列,然后保存了当前运行的线程对象。
    
    看完这些,大概就知道这么一些信息,Looper对象准备好了,消息队列也准备好了,下面我们看消息的发送又做了什么呢?
    
        Message msg=Message.obtain();
        msg.what=UPDATE;
        mHandler.sendMessage(msg);

    //先获得一个消息对象,设置参数,发送消息,我们主要看sendMessage(msg)的源码干了什么事情.

    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);//调用的是这个方法
    }
    //继续
    
    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);
    }

    我们发现它获得了一个消息队列的引用,mQueue又是谁呢?阅读源码你会发现,这个消息队列就是Looper中创建的,然后调用了enqueueMessage(queue, msg, uptimeMillis);//继续深入下去
    
   private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;//把Handler自身设置为Messge中的msg的引用,也就是说,每个消息对象都持有Handler的引用,因为后面要回调Handler的处理方法.
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

   //最后它有调用了消息队列的enqueueMessage(msg, uptimeMillis);方法,我们继续.
   MessageQueue的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(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) {
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                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;
    }

    //我们看到这里其实就是对消息做时间上的排序,这样就完成了消息的入队操作,好了分析完了,到此我们的分析就结束了,谢谢大家。。。。开个玩笑,你们可能会纳闷了,你只是负责发送了消息,消息并没有被处理啊,对了,这就是我接下来要讲的,我们去Looper类中看看有没有什么发现,最后我发现了loop方法,呈上源代码如下:
    
 public static void loop() {
        final Looper me = myLooper();//这就是获得就是你之前设置进去的线程相关的Looper对象
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();
        
        //从这里开始进入了一个死循环
        for (;;) {
            Message msg = queue.next(); // might block//从消息队列获得一个消息
            if (msg == null) {
                return;
            }
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                msg.target.dispatchMessage(msg);//调用Handler的分发消息的 
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

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

        看关键的代码,我们最终注意到了msg.target.dispatchMessage(msg);这个方法,赶紧进去看看它的源码吧,msg.target是谁呢,一路分析的来,我们应该很清楚,这个就是你创建出来的Handler对象,
        因为我之前就说过了,每个Messge对象都会保存一个Handler的引用,看下面你的代码
        
        public void dispatchMessage(Message msg) {
        if (msg.callback != null) {//这里的CallBack对象就是新建Handler可能传过来的对象
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {//这里mCallback同理也可能是你自己传入的CallBack接口类型的对象
                    return;
                }
            }
            handleMessage(msg);
        }
    }
    这下你应该很清楚了吧,最终每个消息要么执行handleCallback(msg)要么执行handleMessage(msg);下面我直接列出它的源码
    handleCallback(msg)源码如下:

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

    }

//直接调用了你的回调方法的run()方法


    handleMessage(msg)源码如下
                                               
    public void handleMessage(Message msg) {
         
    }

//对,我没有逗你,这就是一个空方法,因为更新UI的操作是要你自己写的,所以需要你重写它,那么问题又来了,我们并没有在Activity的主线程调用过Looper.prepare方法来准备Looper对象,也没有调用Loop对象的loop()方法,你怎么就可以直接发消息呢, 你的消息队列也还没准备好不是,你又怎么可以取出消息然后处理消息呢,实际上这些系统都帮我们准备好了,看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对象,用来对消息的轮询;消息队列,用来存消息
    }  
    Looper.loop(); //开始对消息轮询,然后处理,调用你的回调函数 
    throw new RuntimeException("Main thread loop unexpectedly exited");  
}  
//这也就是为什么当我们直接在子线程里面兴建一个Handler的时候会报错提示没有调用Looper.prepare()方法的原因。

总结:长话短说,就是Handler发送Message消息,Looper负责创建消息队列,Handler发的消息最后都会按时间排序存在消息队列中,然后Looper轮询取出消息,将消息重新派发给Handler,然后Handler要干什么就取决于开发者写什么样的逻辑了,这里要说明的一点就是,Handler是在主线程创建的,因此Handler里面的操作都是可以实现UI更新操作的,这就是异步消息的运作原理,总结的不好还请见谅,毕竟菜鸟.