通过handler类向线程的消息队列发送消息

/*
*通过handler类向线程的消息队列发送消息,
*每个Handler对象中都有一个Looper对象和MessageQueue对象
*/
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());
        }
    }
    //获取Looper对象
    mLooper = Looper.myLooper(); 
    if (mLooper == null) {...}
    //获取消息队列
    mQueue = mLooper.mQueue;  
    mCallback = callback;
    mAsynchronous = async;
}

/*
*多种sendMessage方法,最终都调用了同一个方法sendMessageAtTime()
*/
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); 
}
    
/*
*1.当Message中的callback不为null时,执行Message中的callback中的方法。这个callback时一个Runnable接口。
*2.当Handler中的Callback接口不为null时,执行Callback接口中的方法。
*3.直接执行Handler中的handleMessage()方法。
*/
public void dispatchMessage(Message msg) {
    // 消息Callback接口不为null,执行Callback接口
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            //Handler Callback接口不为null,执行接口方法
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        //处理消息
        handleMessage(msg); 
    }
}

发布了37 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/OneLinee/article/details/89300632