Android消息机制

2017-06-27  本文已影响0人  等于空集

Android系统中的视图组件并不是线程安全的,如果要更新视图,必须在主线程中更新,不可以在子线程中执行更新的操作。在子线程中通知主线程我们需要使用到handler对象。

//更新视图

private Handler handler =new Handler() {

    @Override

    public void handleMessage(Message msg) {

        if(msg.what == COMPLETED) {

            stateText.setText("completed");

        }

    }

};

只要在Thread中处理复杂的任务,然后通过handler对象告知主线程,就可以解决线程安全问题。这个过程中,消息机制起着重要的作用。Android通过Looper、Handler来实现消息循环机制。Android的消息循环是针对线程的,每个线程都可以有自己的消息队列和消息循环。


Looper

Looper的作用是关联起Thread和循环取出消息,Looper构造方法是私有的,其中做了两件事:创建一个MessageQueue与得到与之对应的Thread。MainLooper是启动Activity创建ActivityThread(并不是一个Thread)时候创建,所以不能多次创建。一个线程对应一个Looper对象,通过ThreadLocal保证一个线程只有一个Looper与之对应,如果多次调用Looper.prepare()则会抛出运行时异常。

private static void prepare(boolean quitAllowed){

    if(sThreadLocal.get() !=null) {// 查看是否有looper与当前线程对应                                                        thrownewRuntimeException("Only one Looper may be created per thread");

    } 

    sThreadLocal.set(new Looper(quitAllowed));

}

当开启一个loop后是一个死循环,从MessageQueue中取出消息,处理消息,但是也有可能退出,在没有消息后退出循环。

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;// 略

    for(;;) {

        Message msg = queue.next();// might block

        if(msg ==null) {// 当没有消息的时候,退出

            // No message indicates that the message queue is quitting.

            return;

        }// 略

   msg.target.dispatchMessage(msg);

  }

Handler

Looper的作用是发送消息到MessageQueue和处理消息。一个Looper对应一个Thread,一个Looper包含一个MessageQueue。当我们创建Handler时就会从当前线程中取出与之对应的Looper,然后再从Looper中取出MessageQueue。

public Handler(Callback callback, boolean async){

    // 略

    mLooper = Looper.myLooper();// 取出当前线程中的Looper

    if(mLooper ==null) {

        throw new RuntimeException("Can't create handler inside thread that has not called Looper.prepare()");

    }

    mQueue = mLooper.mQueue;// 取出MessageQueue

    mCallback = callback;

    mAsynchronous =async;

}

public Handler(Looper looper, Callback callback, boolean async){

        mLooper = looper;

        mQueue = looper.mQueue;

        mCallback = callback; 

       mAsynchronous =async;

    }

Message

消息机制中的message是单链表结构,作用是作为数据的载体传递。Message有一个成员变量,他的类型正是Handler,当我们通过Handler去send一个Message时候最终都会为这个成员变量赋值为this,即当前的Handler。另为如果是通过Message.Obtain(),获取的复用Message也会为其赋值。

private boolean enqueueMessage(MessageQueue queue, Message msg,long uptimeMillis){        msg.target =this;// 赋值语句

    if(mAsynchronous) {

        msg.setAsynchronous(true);

    }

    return queue.enqueueMessage(msg, uptimeMillis);

}

总结

通过一系列的包涵关系,最终Looper、Handler、Message、MessageQueue即发生关联,从而形成一个闭合,开启消息循环。

上一篇 下一篇

猜你喜欢

热点阅读