Android消息处理机制---Looper、Handler、Message之间的关系

从一个应用程序的实例来理解安卓线程间的通信比较容易,这个消息处理机制在Android源码中被大量用到。
class MyThread extends Thread {
    private Looper mLooper;
    @Override
    public void run() {
        super.run();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Looper.loop();
    }·

    public Looper getLooper(){
        if (!isAlive()) {
            return null;
        }

        // If the thread has been started, wait until the looper has been created.
        synchronized (this) {
            while (isAlive() && mLooper == null) {
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }
}

myThread2 = new MyThread();
myThread2.start();

mHandler = new Handler(myThread2.getLooper(), new Handler.Callback() {
    @Override
    public boolean handleMessage(Message msg) {
        Log.d(TAG, "get Message "+ mMessageCount);
        mMessageCount++;
        return false;
    }
});
先实例化MyThread对象,再启动线程:
myThread2 = new MyThread();
myThread2.start();
新的线程在执行start方法后,myThread2的run方法被执行,首先执行父类的run方法,然后执行Looper.prepare();文件frameworks/base/core/java/android/os/Looper.java中定义了Looper类,其中对prepare方法定义如下:
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));
}
sThreadLocal在Looper类中的定义如下:
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
它是一个ThreadLocal对象,可以在一个线程中存储变量。通过 if (sThreadLocal.get() != null)来保证Looper.prepare()方法不能被调用两次,即一个线程中只有一个Looper类的实例。sThreadLocal.set(new Looper(quitAllowed));新建了一个匿名Looper对象,并设置这个匿名Looper对象为当前线程的Looper实例,Looper类的构造方法如下:
private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
}
它为当前线程新建了一个消息队列,这个消息队列是Looper和Handler沟通的关键。
回到MyThread2的run方法,接下来执行mLooper = Looper.myLooper();来获得之前新建线程的Looper对象,myLooper方法定义如下:
public static @Nullable Looper myLooper() {
       return sThreadLocal.get();
}
接下来的notifyAll();的作用在后面解释,最后调用Looper.loop();让线程休眠,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.recycleUnchecked();
    }
}
在loop方法中,首先通过myLooper方法获得当前线程的Looper实例,myLooper方法在前面介绍过,最后进入循环,通过Message msg = queue.next();不断取出消息队列里面的消息,如果没有消息,就休眠,有消息调用后面的msg.target.dispatchMessage(msg);来执行消息的响应函数,消息的响应函数由Hander指定,消息也由Hander构造,这个在后面分析。

现在回到app程序,在新建的myThread2线程调用start方法运行之后,新建了Handler对象,Handler类在frameworks/base/core/java/android/os/Handler.java文件中定义,它的构造方法如下:
public Handler(Looper looper, Callback callback) {
    this(looper, callback, false);
}

public Handler(Looper looper, Callback callback, boolean async) {
    mLooper = looper;
    mQueue = looper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}
由此可见,在构造方法中,将myThread2的Looper对象传给了Handler对象的mLooper属性,并将前面Looper创建的消息队列传递给了Handler,并指定了消息的处理函数handleMessage,以后Handler发送消息后,Looper对象就会调用handleMessage方法来处理消息。发送消息的方法如下:
Message msg = new Message();
mHandler.sendMessage(msg);
Handler的sendMessage方法如下:
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);
}

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}
很明显,最后调用sendMessageAtTime方法将新建的消息通过enqueueMessage方法放入Looper新建的消息队列中,在enqueueMessage方法中,它将消息的target指定为当前的Handler。当消息被放到消息队列后,休眠的线程会被唤醒,执行for循环中的msg.target.dispatchMessage(msg);Handler的dispatchMessage方法如下:
public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}
这里,msg的callback为null,Handler的mCallback属性在前面的构造方法中被设置,所以会调用mCallback.handleMessage(msg);来处理消息,也就是在app中新建Handler对象时传入的第二个形参的Callback接口:
@Override
public boolean handleMessage(Message msg) {
    Log.d(TAG, "get Message "+ mMessageCount);
    mMessageCount++;
    return false;
}
下面分析前面提到的notifyAll();在新建Handler的对象时,需要获得当前线程的Looper实例,就是通过myThread2.getLooper()来获得,在MyThread2线程的run方法中,返回这个Looper实例,如果mLooper还没有被run方法设置,那么在执行myThread2的getLooper方法时就会休眠,直到myThread2的run运行结束,通过notifyAll();来唤醒。

当然,Handler发送消息时,有许多方法,比如post方法:
mHandler3.post(new Runnable() {
                @Override
                public void run() {
                    Log.d(TAG, "get Message for Thread3 "+ mMessageCount);
                    mMessageCount++;
                }
            });
post方法实现如下:
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;
}

这个时候,新建Handler对象时,只需传入Looper对象:

mHandler3 = new Handler(myThread3.getLooper());

Android线程间通信的总结:
1.新开的线程从Thread类继承,通过Looper类的prepare方法sThreadLocal.set(new Looper(quitAllowed));来新建一个Looper对象,并且通过sThreadLocal.set方法来保存该Looper对象,以后就可以通过sThreadLocal.get方法来获得该Looper对象。
2.在Looper类的构造方法中,它通过mQueue = new MessageQueue(quitAllowed);新建一个消息队列,之后线程执行Looper.loop来休眠。
3.在主线程中,新建一个Handler对象,并将之前新建线程的Looper对象和消息队列传递给该Handler。消息由该Handler构造,消息的执行方法也由该Handler指定。
4.当主线程需要发消息给新开的线程时,只需调用发送消息的方法即可:Handler的post或者sendMessage。
5.当消息队列中有消息时,新线程被唤醒,执行Message msg = queue.next();来从消息队列中取出消息,然后调用msg.target.dispatchMessage(msg);来执行由Handler指定的消息响应函数,执行完毕后继续休眠。
6.循环执行步骤4和5。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值