简单粗暴理解android异步消息处理机制

     /** Initialize the current thread as a looper.
      * This gives you a chance to create handlers that then reference
      * this looper, before actually starting the loop. Be sure to call
      * {@link #loop()} after calling this method, and end it by calling
      * {@link #quit()}.
      */
    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));
    }

Looper类中,sThreadLocal是一个ThreadLocal对象,可以在一个线程中存储变量,将一个Looper的实例放入了ThreadLocal,可以看出,多次调用prepare()会抛异常。ThreadLocal对象解释如下:

/**
 * Implements a thread-local storage, that is, a variable for which each thread
 * has its own value. All threads share the same {@code ThreadLocal} object,
 * but each sees a different value when accessing it, and changes made by one
 * thread do not affect the other threads. The implementation supports
 * {@code null} values.
 *
 * @see java.lang.Thread
 * @author Bob Lee
 */
public class ThreadLocal<T> {

    /* Thanks to Josh Bloch and Doug Lea for code reviews and impl advice. */

    /**
     * Creates a new thread-local variable.
     */
    public ThreadLocal() {}
Looper构造方法:
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }
消息队列MessageQueue是在new Looper的时候新建的
loop方法:

    /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the 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.");}//可见loop()方法一定要在Looper.prepar///之后调用
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre">		</span></span><span style="font-family: Arial, Helvetica, sans-serif;">final MessageQueue queue = me.mQueue;//从Looper实例中拿出来消息队列(消息队列在Looper中新建的嘛)</span><span style="font-family: Arial, Helvetica, sans-serif;">
</span>
        // 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);
            }

<span style="white-space:pre">	</span>msg.target.dispatchMessage(msg);// 后面handler类中有最终处理消息msg.target = this;msg.target就是handler,所有这句调handler的dispatch

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

    /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static Looper myLooper() {
        return sThreadLocal.get();
    }
将之前放进去的Looper的从ThreadLocal拿回来。
主线程绑定主线程的Looper,一个线程绑定一个Looper,一个Looper示例只有一个消息队列,loop()方法阻塞线程,显然要在子线程调用,在子线程无限循环取消息,拿到消息给handler,handler在主线程处理消息。再看handler类:

    /**
     * Use the {@link Looper} for the current thread with the specified callback interface
     * and set whether the handler should be asynchronous.
     *
     * Handlers are synchronous by default unless this constructor is used to make
     * one that is strictly asynchronous.
     *
     * Asynchronous messages represent interrupts or events that do not require global ordering
     * with represent to synchronous messages.  Asynchronous messages are not subject to
     * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
     *
     * @param callback The callback interface in which to handle messages, or null.
     * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
     * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
     *
     * @hide
     */
    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();//这个方法从主线程(handler在主线程实例化的时候)取出主线程Looper实例(return sThreadLocal.get();)
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
       mQueue = mLooper.mQueue;//handler成功关联上了消息队列
        mCallback = callback;
        mAsynchronous = async;
    }
    public static Looper myLooper() {
        return sThreadLocal.get();
    }
看消息处理:
 public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, delayMillis);
    }
 
    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);
    }

最终都是走的sendMessageAtTime;并在这里面处理队列的消息:

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
       msg.target = this;//this就是这个类handler对象,把handler给到msg消息的target、
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
       return queue.enqueueMessage(msg, uptimeMillis);//这句保存消息,handler发出的消息最终保存在这里这个消息队列里面。
    }

loop()方法中有
msg.target.dispatchMessage(msg);// 后面handler类中有最终处理消息msg.target = this;msg.target就是handler,所有这句调handler的dispatch

所以这就通了loop方法中会取出消息,交给handler的dispatchMessage方法来处理消息。
    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
       if (msg.callback != null) {//msg.callback就是handler.post(runnable)的runable
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);//源码中这个方法是空方法,所以我们new handler是要复写这方法
        }
    }

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

Looper.prepare()在本线程(咱们说的是主线程looper,一般说的UI线程)中保存一个Looper(内部实现一个消息队列,达到线程looper消息队列一对一对应)实例,handler的sendMessage方法最终会给message的targe赋值为handler自身,相当于标记,然后加入消息队列,Looper.loop()(一定要注意在子线程)无限循环,从消息队列取消息,根据标记targe取出来handler,回调handler的dispatchMessage,而在Handler的构造方法中,会首先得到当前线程中保存的Looper实例,与Looper实例中MessageQueue相关联。Looper.prepare()和Looper.loop()方法在Activity的启动代码中,在当前UI线程调用了。

ActivityThread(frameworks\base\core\java\android\app\ActivityThread.java)

public final class ActivityThread {  
    // 省略一大坨代码  
    public static void main(String[] args) {  
        SamplingProfilerIntegration.start();  
  
        CloseGuard.setEnabled(false);  
  
        Environment.initForCurrentUser();  
  
        EventLogger.setReporter(new EventLoggingReporter());  
  
        Security.addProvider(new AndroidKeyStoreProvider());  
  
        Process.setArgV0("<pre-initialized>");  
  
        Looper.prepareMainLooper();  
  
        <strong>ActivityThread thread = new ActivityThread();  
        thread.attach(false);  
  
        if (sMainThreadHandler == null) {  
            sMainThreadHandler = thread.getHandler();  
        }</strong>  
  
        AsyncTask.init();  
  
        if (false) {  
            Looper.myLooper().setMessageLogging(new  
                    LogPrinter(Log.DEBUG, "ActivityThread"));  
        }  
  
        Looper.loop();  
  
        throw new RuntimeException("Main thread loop unexpectedly exited");  
    }  
}  
/**
 * Handy class for starting a new thread that has a looper. The looper can then be 
 * used to create handler classes. Note that start() must still be called.
 */
public class HandlerThread extends Thread {
    int mPriority;
    int mTid = -1;
    Looper mLooper;

    public HandlerThread(String name) {
        super(name);
        mPriority = Process.THREAD_PRIORITY_DEFAULT;
    }
    
    /**
     * Constructs a HandlerThread.
     * @param name
     * @param priority The priority to run the thread at. The value supplied must be from 
     * {@link android.os.Process} and not from java.lang.Thread.
     */
    public HandlerThread(String name, int priority) {
        super(name);
        mPriority = priority;
    }
    
    /**
     * Call back method that can be explicitly overridden if needed to execute some
     * setup before Looper loops.
     */
    protected void onLooperPrepared() {
    }

    @Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }
looper在ui线程中 但是他是一个单独的线程 (因为他继承了Thread)所以 ui线程不会因为looper阻塞(姑且这么理解,有待考证)主线程一直在处理消息,没空干别的,所以别处理耗时任务,否则ANR。
必须要源代码。read the fucking source code。消息处理机制代码并不多,一定要看了源代码才能加深理解。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值