消息机制

异步消息处理

一、Looper

Looper负责的就是创建一个MessageQueue,然后进入一个无限循环体不断从该MessageQueue中读取消息,而消息的创建者就是一个或多个Handler 。

在构造方法中,创建了一个MessageQueue(消息队列)。

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

方法1. static void prepare() 静态的方法,准备
ThreadLocal中添加进一个新的对象,sThreadLocal是一个ThreadLocal对象,可以在一个线程中存储变量。prepare()中判断了当前线程的 Looper 对象是否为null,不为 null则抛出异常。这也就说明了一个线程Looper.prepare()方法不能被调用两次,同时也保证了一个线程中只有一个Looper实例

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
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));
}

方法2. loop() 方法

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

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);把消息交给msg的target的dispatchMessage方法去处理。
        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();
    }
}

Looper 的静态方法 prepare() 中新建了一个 Looper 对象,Looper 的构造方法中初始化了 MessageQueue(新建) 和 Thread (当前线程)。这两个对象是 Looper 对象持有的,每个 Looper 对象中都有一个 MessageQueue 和 当前线程对象

prepare() 中将新建的 Looper 对象添加到了 ThreadLocal<Looper> 对象中,这个对象是
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
ThreadLocal<Looper> 在类的最初就会实例化,在存储 Looper 的时候会以当前线程的对象作为一个参数,在取Looper
时也会通过当前线程来取

prepare() 方法中会判断当前线程是否已经绑定了 Looper 对象,如果绑定了则会抛出
throw new RuntimeException("Only one Looper may be created per thread");
并且在取 Looper 时也会根据当前线程判断是否绑定了 Looper ,如果没有绑定则会抛出
throw new IllegalStateException("No Looper; Looper.prepare() wasn't called on this thread.");
通过这个过程,保证了每个线程只能绑定一个 Looper ,并且每个 Looper 都有一个 MessageQueue 对象

Looper.myLooper()获取了当前线程保存的 Looper 实例,然后在又获取了这个 Looper 实例中保存的
MessageQueue(消息队列),这样就保证了 handler 的实例与我们 Looper 实例中 MessageQueue 关联上了。

Looger.getMainLooper(); 获取主线程的 Looper 对象,主线程会自动调用 Looper.prepareMainLooper() 方法
完成 Looper 对象的绑定,并将该 Looper 对象赋值给一个静态的 Looper 变量,在调用 getMainLooper() 方法
时将该 Looper 对象返回。
Looper.myLooper() 方法是获取当前线程的 Looper 对象。

Looper主要作用:

  1. 与当前线程绑定,保证一个线程只会有一个Looper实例,同时一个Looper实例也只有一个MessageQueue。
  2. loop()方法,不断从MessageQueue中去取消息,交给消息的target属性的dispatchMessage去处理。
    好了,我们的异步消息处理线程已经有了消息队列(MessageQueue),Looper 负责轮询消息队列,下面分析发送消息的 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;
}

Handler 对象中有一个 Looper 对象和一个 MessageQueue 对象,这两个属性都是final 的
在创建一个 Handler 对象的时候,如果当前线程没有绑定 Looper 对象,则会抛出异常
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
所以在一个线程中创建 Handler 的时候当前线程必须调用 Looper.prepare(); 方法

然后看我们最常用的sendMessage方法,方法最后调用了sendMessageAtTime,在此方法内部有直接
获取 MessageQueue 然后调用了 enqueueMessage 方法,我们再来看看此方法: enqueue : 入队

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

enqueueMessage 中首先为 meg.target 赋值为this,【Looper的loop方法会取出每个msg然后交给
msg.target.dispatchMessage(msg) 去处理消息】,也就是把当前的handler作为msg的 target 属性。最终
会调用 queue 的 enqueueMessage 的方法,也就是说 handler 发出的消息,最终会保存到消息队列中去。enqueueMessage 方法中使用 synchronize 锁 MessageQueue 对象,保证不同线程插入数据时的同步问题。

Looper会调用prepare()和loop()方法,在当前执行的线程中保存一个Looper实例,这个实例会保存一个
MessageQueue对象,然后当前线程进入一个无限循环中去,不断从MessageQueue中读取Handler发来的消息。
然后再回调创建这个消息的handler中的dispathMessage方法,下面我们赶快去看一看这个方法:

public void dispatchMessage(Message msg) {  
    if (msg.callback != null) {  
        handleCallback(msg); // 使用创建 Message 时构造方法中的 Runnable 处理消息
    } else {  
        if (mCallback != null) {  
            if (mCallback.handleMessage(msg)) {  // 使用创建 Handler 时构造方法中的 Handler.Callback 处理消息
                return;  
            }  
        }  
        handleMessage(msg);  // 重写的处理消息方法处理
    }  
} 

这个流程已经解释完毕,让我们首先总结一下

  1. 首先Looper.prepare()在本线程中保存一个Looper实例,然后该实例中保存一个MessageQueue对象;
    因为Looper.prepare()在一个线程中只能调用一次,所以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)最终调用的方法。

好了,总结完成,大家可能还会问,那么在Activity中,我们并没有显示的调用Looper.prepare()和Looper.loop()方法,
为啥Handler可以成功创建呢,这是因为在Activity的启动代码中,已经在当前UI线程调用了Looper.prepareMainLooper()和Looper.loop()方法。

关于Handler处理消息的方式

  1. 创建Message对象时,指定Runnable对象,
    例如Message.obtain(Handler handler, Runnable callback)
  2. 创建Handler.Callback实现类对象,并作为创建Handler的构造方法的参数
  3. 自定义类继承自Handler,并重写handlerMessage()方法
    以上3种方法的执行顺序:如果存在方式1,则由方式1直接处理;如果存在方式2,
    则方式2处理消息,且,如果方式2返回true,则处理完毕,否则,方式3也会处理消息。

Handler.post(); // 等多久执行... run() 方法中的代码

mHandler.post(new Runnable() {  
    @Override      
    public void run(){  
        og.e("TAG", Thread.currentThread().getName());  
        mTxt.setText("test");  
    }  
});  

然后run方法中可以写更新UI的代码,其实这个Runnable并没有创建什么线程,而是发送了一条消息,下面看源码:

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

可以看到,在getPostMessage中,得到了一个Message对象,然后将我们创建的Runable对象作为callback属性,赋值给了此 message.

  • 注:产生一个Message对象,可以new ,也可以使用Message.obtain()方法;两者都可以,但是更建议使用obtain方法,
    因为Message内部维护了一个Message池用于Message的复用,避免使用new 重新分配内存。
    最终和handler.sendMessage一样,调用了sendMessageAtTime,然后调用了enqueueMessage方法,给msg.target赋值为 handler,最终加入MessagQueue.

  • msg的 callback 和target都有值,那么会执行哪个呢?
    如果 callback 不为null,则执行callback回调,也就是我们的Runnable对象

  • Handler 对象创建之后可以在任何线程中发消息,最终消息的处理都将回到 创建 Handler 时使用的 Looper 所在的线程处理。所以在子线程中可以使用主线程中创建的 Handler 对象发消息,在主线程中处理消息。
  • Activity 中可以创建多个 Handler ,处理消息时就调用 msg.targe 也就是 Handler 来处理.Looper 将消息发送给发送消息时使用的 Handler 对象。
    子线程不可以直接创建 Handler, 必须在子线程先调用 Looper.prepare();线程中调用 Looper.loop(); 方法后才会开启轮循

  • 一个线程中只能有一个 Looper ,也就是只能有一个 MessageQueue ,可以有多个 Handler。一个 Handler 可以在不同的线程中发送消息,但是消息的处理都是在创建 Handler 时使用的 Looper 所在的线程。

参考:http://blog.csdn.net/lmj623565791/article/details/47079737

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

推荐阅读更多精彩内容