消息机制

zygote是受精卵的意思,在Android系统中表示建新进程的核心进程. 新进程在初生之时,就先天具有了自己的Dalvik虚拟机以及系统资源. 每个新的Android应用进程在启动时都会创建一个线程,这就是我们的UI线程或说是主线程。每个线程都有独立的ThreadLocal变量,保存本线程的数据信息。

下面我们从android应用程序的入口ActivityThread类的main方法说起:

public static void main(String[] args) {
    Looper.prepareMainLooper();
    ActivityThread thread = new ActivityThread();
    thread.attach(false);
    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }
    Looper.loop();      
}

从代码中我们可以看到主线程会关联一个消息队列。


public final class Looper {
    private static final String TAG = "Looper";
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    private static Looper sMainLooper;  // guarded by Looper.class
    final MessageQueue mQ
    // 准备工作     
    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));
    }
    // UI线程消息循环的准备工作
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

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

    public static void loop() {
        final Looper me = myLooper();
        .....
        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            ......
        }
    }

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

    public static @NonNull MessageQueue myQueue() {
        return myLooper().mQueue;
    }
}

从代码中我们了解到每个线程的MessageQueue以及Loop实例都是保存在该线程的ThreadLocal中,并且只能通过该线程的ThreadLocal获取。

下面我们来研究系统是如何将消息投递到消息队列并处理:答案的是Handler。

public Handler() {
    this(null, false);
}
public Handler(Looper looper) {
    this(looper, null, false);
}
public Handler(Callback callback, boolean async) {
    mLooper = Looper.myLooper();      // 获取Looper
    if (mLooper == null) {
         // 异常处理
    }
    mQueue = mLooper.mQueue;        // 获取消息队列
    mCallback = callback;
    mAsynchronous = async;
}

handler初始化时都会将该线程的Looper与之关联起来,因此如果要在线程中创建handler则必须先创建该线程的Looper变量,否则会爆空指针异常。就这样Handler就与线程关联起来。

下面我们从具体的代码中分析消息发送及处理这个过程:

Handler.class

// 发送消息
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) {
        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);
}

MessageQueue.class

boolean enqueueMessage(Message msg, long when) {
    ....
    synchronized (this) {
        if (mQuitting) {
            msg.recycle();
            return false;
        }

        msg.markInUse();
        msg.when = when;
        Message p = mMessages;
        boolean needWake;
        if (p == null || when == 0 || when < p.when) {
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked;
        } else {
            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;
        }
    }
    return true;
}

到此之后交由Looper处理该消息。

try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

msg.target其实就是我们刚才那个handler

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

所以我们可以再handler的handleMessage方法中编写处理该消息的逻辑。

转载于:https://my.oschina.net/u/3342652/blog/1554648

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值