Android消息机制

构造

Handler的成员域包含有LooperMessageQueue,如下:

public class Handler {
   .....
    final Looper mLooper;
    final MessageQueue mQueue;
    final Callback mCallback;
    final boolean mAsynchronous;
    IMessenger mMessenger;
  ....

   public interface Callback {
        public boolean handleMessage(Message msg);
    }
}

在构造Handler的时候需要用初始化mLoopermQueue,如果用户传入了Looper,就会用传入的Looper作为初始化参数,否则会以当前所现在线程的Looper为初始化参数,而用于初始化mQueue的MessageQueue 参数是正是从用于初始化mLooper的Looper中来的。

    //没有传入Looper的构造函数
    public Handler() {
        this(null, false);
    }
   //没有传入Looper的构造函数
   public Handler(Callback callback) {
        this(callback, false);
    }
  //没有传入Looper的构造函数
   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());
            }
        }
        //用户当前线程的Looper,采用ThreadLocal来处理的
        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;
    }
  //传入Looper的构造函数
    public Handler(Looper looper) {
        this(looper, null, false);
    }
  //传入Looper的构造函数
     public Handler(Looper looper, Callback callback) {
        this(looper, callback, false);
    }
    //传入Looper的构造函数
    public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

而Looper中的MessageQueue类型的成员域mQueue则是在构造的时候被初始化的:

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

显然Looper的构造函数为私有,要想初始化Looper,Looper提供了prepare()prepareMainLooper()这两个静态方法,分别用于在当前线程和主线程中初始化Looper.

   //当前线程初始化Looper
   public static void prepare() {
        prepare(true);
    }

  //主线程中初始化Looper,该方法会在ActivityThread的main方法中自动调用,不能我们自己方法中手动调用该方法
  public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {//只能初始化一次
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

  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));//此处在调用构造方法
    }

当初始化以后,可以通过getMainLooper()myLooper()静态方法分别拿到主线程的Handler和当前线程的Looper.


 public static Looper getMainLooper() {
        synchronized (Looper.class) {
            return sMainLooper;
        }
    }

public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

由于prepareMainLooper()会在APP启动过程中通过ActivityThread的入口main方法中调用,因此再回到Handler的构造函数中,当我们在Activity或者Service中直接用new Handler()或者其他不带Looper的构造函数或者传入的Looper是通过Looper.getMainLooper()拿到的,该Handler只会处理主线程中的消息,该Handler中的Looper是由prepareMainLooper()创建的,如此就将Handler、Looper和MessageQueue关联起来了。

发消息

Handler发消息最终会调用它的enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis)方法并将发送的消息和发送消息的Handler关联起来


   private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;//将当前Handler对象绑定到后期处理消息的Handler上,当消息处理完成之后会调用  msg.target.dispatchMessage(msg);
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

Handler在委托给MessageQueue 的boolean enqueueMessage(Message msg, long when)方法,MessageQueue 会将消息按照时间先后顺序放入消息队列(实际上是一个单链表,插入和删除数据的代价会低一些,如果遍历只能从头到尾遍历)

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

取消息

消息是在Looper的loop()方法的一个无线循环中调用MessageQueue的next()获取得到

   public final class Looper {
      ...
   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
            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的dispatchMessage方法
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

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

现在我们需要知道Looper的loop()方法何时调用,如果是在主线程中,则会在ActivityThread的入口函数中调用main调用,部分代码如下所示:

public final class ActivityThread {
   ...
  public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
             .....
        Looper.prepareMainLooper();//调用prepareMainLooper方法初始化主线程Looper
        ActivityThread thread = new ActivityThread();
        thread.attach(false);
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }
        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();//调用loop方法(说明一直是阻塞在这里没有继续往下面执行,否则会抛出异常)

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
  ...
}

如果是在某一个子线程中,可遵照Handler的注释文档给出的形式,如下所示

      class MyLooperThread extends Thread {
        public Handler mHandler;
        public void run() {
            Looper.prepare();
            mHandler = new Handler() {
                public void handleMessage(Message msg) {
                    // process incoming messages here
                   //如果要将该消息发送到主线程,在此处用主线程中的Handler 来发送,如:mUiHandler.sendMessage(msg);
                }
            };
            Looper.loop();
        }
    }

Android提供了HandlerThread,无需手动调用loop(),参见IntentService源码。
在MessageQueue的获取消息的next()方法中,调用了一个java native方法private native void nativePollOnce(long ptr, int timeoutMillis),native的部分实现(参见MessageQueue.cpp):

static void android_os_MessageQueue_nativePollOnce(JNIEnv* env, jobject obj,
        jlong ptr, jint timeoutMillis) {
    NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
    nativeMessageQueue->pollOnce(env, obj, timeoutMillis);
}

void NativeMessageQueue::pollOnce(JNIEnv* env, jobject pollObj, int timeoutMillis) {
    mPollEnv = env;
    mPollObj = pollObj;
    mLooper->pollOnce(timeoutMillis);
    mPollObj = NULL;
    mPollEnv = NULL;

    if (mExceptionObj) {
        env->Throw(mExceptionObj);
        env->DeleteLocalRef(mExceptionObj);
        mExceptionObj = NULL;
    }
}

不难看出调用的是native层的Looper类的pollOnce方法,参见(Looper.cpp)的pollOnce方法,因里面用到著名的Linux的epoll机制,这一块我不太清楚因此目前没法继续深入下去了(o(╥﹏╥)o),先占个坑,希望以后能搞定

处理消息

由于处理消息是在Looper的loop()方法调用Handler的dispatchMessage(Message msg)方法,因此进入到Handler的这个方法签名下面:

public class Handler {
  ...
   public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }
  //这是需要重新覆盖的方法
   public void handleMessage(Message msg) {
    }
   private static void handleCallback(Message message) {
        message.callback.run();//callback是Runnable类型
    }
...
}

不难看出,处理消息的时候,先看Message的callback是否存在,如果存在就用直接调用回调callback,如果不存在,检查Handler的成员域mCallback 是否存在,存在就回调,在构造一节可知mCallback是在构造函数中传入的,不再在就调用用户实现的handleMessage方法。

总结

Handler发送Message的实际只是将Message按照处理时间先后顺序存放到MessageQueue中并将发送的Message和该Handler相关联,在Looper的loop方法循环调用MessageQueue的next()获取可处理的Message,取出的Message在通过之前关联的Handler来处理。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容