android的消息与线程

需要认清的四个主要组成部分是:

Looper

Message

MessageQueue

Handler

 

一个线程如果需要接受来自其他线程的消息,并且加以处理的话,就必须使用Looper来为这个线程添加一个消息队列,即MessageQueue


Looper的四个主要方法:

public static prepare();

public static myLooper();

public static loop();

public void quit();

在线程的run方法中,一开始使用Looper.prepare()为这个线程添加一个LooperLooper含有成员MessageQueue,这样线程就拥有了消息队列。为了处理消息,还需要自定义Handler,完成其中的handleMessage方法来处理发送给这个Handler的消息。定义完Handler后,使用Looper.loop()使消息队列开始运作,就可以接收消息了。

由于有时需要判断线程是否有绑定Looper,使用静态方法myLooper可以获得该线程绑定的Looper对象,另外quit方法不向之前的几个方法是静态的,通过myLooper获得对象后,对象调用quit方法就可以结束消息循环。


下面是对源码的分析:

public final class Looper {
    /*
     * API Implementation Note:
     *
     * This class contains the code required to set up and manage an event loop
     * based on MessageQueue.  APIs that affect the state of the queue should be
     * defined on MessageQueue or Handler rather than on Looper itself.  For example,
     * idle handlers and sync barriers are defined on the queue whereas preparing the
     * thread, looping, and quitting are defined on the looper.
     */

    private static final String TAG = "Looper";

    // sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal
   
   
    
     sThreadLocal = new ThreadLocal
    
    
     
     ();
    private static Looper sMainLooper;  // guarded by Looper.class

    final MessageQueue mQueue;
    final Thread mThread;

    private Printer mLogging;
    
    
   
   

成员变量中:

sThreadLocal是一个ThreadLocal,用于保存每个线程的副本,方便线程对自己做出更改而不会影响到其他线程

mQueue就是该Looper的消息队列,使用FIFO方法

mThread是与该Looper绑定的线程


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));
}
prepare 方法有一个参数是 quitAllowed ,表示是否允许该 Looper 退出,默认为 true 。可以看到,一个线程是只能调用一次 prepare 的,也就是只能有一个 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
        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.recycleUnchecked();
    }
}

在调用loop方法时,先用myLooper获得Looper对象来确定是否创建了Looper,然后进入无限for循环,也就是消息队列循环开始。

在循环中,queue.next()取出下一个消息,如果为空,说明正在推出消息队列,return;结束loop(事实上,MessageQueuenext方法是耗时的,其中也是有一个无限循环,当调用next方法且队列中没有消息时,MessageQueue会一直等待直到接收到新的消息并返回,但是循环前,MessageQueue会检查是否已退出,如果已退出就会立刻返回null

如果不为空,msgtarget成员调用dispatchMessage发送该消息,target成员即是目标Handler对象,这里相当于给自己发消息。

最后消息对象调用recycleUnchecked方法回收自己,在该方法中,消息所携带的所有信息(或者说是成员)都会被置零或者置空,然后将自己加入到回收消息链表中。PS.使用Message时最好用回收的消息,尽量不要创建新对象,避免不必要的资源浪费。


public static @Nullable Looper myLooper() {
    return sThreadLocal.get();
}
调用 myLooper 时,静态的sThreadLocal调用 get 方法获得该 Looper


public void quit() {
    mQueue.quit(false);
}
调用 quit 方法就是 MessageQueue 调用 quit 方法,该方法会将队列中的所有消息回收

那么为什么在遍写活动的时候不用手动创建Looper呢?这是因为已经加载了一个ActivityThread对象了,其中就是创建了一个Looper,并且是mainLooper

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值