Android中Looper,Message和Handle之间的简要关系说明

Looper:
一个线程只能存在一个Looper实例,在Activity创建的时候系统已经帮我们自动创建好了一个,并且生成一个MessageQueue。
期间主要用到的方法有:prepare()和loop()。
prepare():生成Looper对象来管理MessageQueue,并且一个Looper对象只能有一个MessageQueue。
loop():从MessageQueue中循环取出消息。
1.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");  
    }  

2.Looper.prepare()方法:
Looper.prepareMainLooper()会再去调用Looper.prepare()方法,代码如下:

    public static final void prepareMainLooper() {  
        prepare();  
        setMainLooper(myLooper());  
        if (Process.supportsProcesses()) {  
            myLooper().mQueue.mQuitAllowed = false;  
        }  
    }  

以上代码为系统自动帮我们实现的,这时候在UI线程中会一直存在这个Looper对象和MessageQueue。
2.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.recycle();  
            }  
    }  

loop()方法,不断从MessageQueue中去取消息,交给消息的target属性的dispatchMessage去处理。

Handler:
通过Handler实例来在子线程中发送消息到MessageQueue,并且在UI线程中通过回调来接收消息。
1.与当前的MessageQueue绑定。

    public Handler() {  
            this(null, false);  
    }  
    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;  
        }  

//sendMessage:

public final boolean sendMessage(Message msg)  
     {  
         return sendMessageDelayed(msg, 0);  
     }

//sendEmptyMessageDelayed:

    public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {  
         Message msg = Message.obtain();  
         msg.what = what;  
         return sendMessageDelayed(msg, delayMillis);  
     }  

//sendMessageDelayed:

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

//enqueueMessage:

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

最后调用到了enqueueMessage这个方法,enqueueMessage中首先将this赋给meg.target,把当前的handler作为msg的target属性,最后调用queue.enqueueMessage将当前msg(handler)加入到消息队列中去。
loop方法会取出每个msg然后交给msg,target.dispatchMessage(msg)去处理消息。

    public void dispatchMessage(Message msg) {  
            if (msg.callback != null) {  
                handleCallback(msg);  
            } else {  
                if (mCallback != null) {  
                    if (mCallback.handleMessage(msg)) {  
                        return;  
                    }  
                }  
                handleMessage(msg);  
            }  
        }  

最终我们就可以在UI线程中处理接收到的消息了。

    private Handler mHandler = new Handler()  
        {  
            public void handleMessage(android.os.Message msg)  
            {  
                switch (msg.what)  
                {  
                case value:  

                    break;  

                default:  
                    break;  
                }  
            };  
        };  

这样整个流程就大体结束了。来整理下思路:
1、Looper.prepare()在生成一个Looper实例,保存一个MessageQueue对象。
2、Looper.loop()会让当前线程进入一个无限循环,不端从MessageQueue中读取消息,然后回调msg.target.dispatchMessage(msg)方法。
3、Handler的构造方法,会首先得到当前线程中保存的Looper实例,进而与Looper实例中的MessageQueue想关联。
4、Handler的sendMessage方法,会给msg的target赋值为handler自身,然后加入MessageQueue中。
5、在构造Handler实例时,我们会重写handleMessage方法,也就是msg.target.dispatchMessage(msg)最终调用的方法。
《参考 Android 异步消息处理机制 让你深入理解 Looper、Handler、Message三者关系Android异步消息处理机制完全解析,带你从源码的角度彻底理解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值