Handler源碼分析

Paste_Image.png

Handler

Handler:負(fù)責(zé)發(fā)送和接收消息

1、創(chuàng)建Handler時(shí)調(diào)用的它的構(gòu)造函數(shù)Handler(null,false),主要獲取當(dāng)前線程的Looper對(duì)象和消息循環(huán)。

    public Handler(Callback callback, boolean async) {
        mLooper = Looper.myLooper();
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }
2、發(fā)送消息sendMessage
  • sendMessage方法,發(fā)送消息最終調(diào)用的是Handler中的enqueueMessage方法,MessageQueue中的enqueueMessage方法,在消息隊(duì)列中通過(guò)msg.when將消息放到合適的位置。
private boolean enqueueMessage(MessageQueue queue, Message msg,
long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
}
    ```
* obtainMessage方法,它是從消息池里面取出一個(gè)消息,沒(méi)有時(shí)才創(chuàng)建消息效率高。
    
* postDelayed方法,此方法需要傳一個(gè)Runnable對(duì)象,最終賦值給Message的callback屬性。

private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}

######3、分發(fā)消息dispatchMessage

public void dispatchMessage(Message msg) {
//如果callback不為空,直接調(diào)用
if (msg.callback != null) {
message.callback.run();
handleCallback(msg);
} else {
//創(chuàng)建Handler時(shí),傳遞的Callback接口,默認(rèn)為null。
if (mCallback != null) {
if (mCallback.handleMesscage(msg)) {
return;
}
}
handleMessage(msg);//回調(diào)子類方法,在Handler類里面只是聲明。
}
}

###Looper:
* 1、ThreadLocal類
    它的作用是為每一個(gè)線程保存一份變量,內(nèi)部其實(shí)用一個(gè)數(shù)組來(lái)表示,對(duì)索引進(jìn)行散列保證內(nèi)部均勻。
    >ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    
* 2、prepare方法準(zhǔn)備操作
    準(zhǔn)備Looper類,在Looper構(gòu)造函數(shù)里面創(chuàng)建消息隊(duì)列和獲取當(dāng)前線程。將線程和Looper進(jìn)行關(guān)聯(lián)起來(lái)。
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));
}
private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}
* 3、loop方法
    使消息進(jìn)行分發(fā)
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) {
            return;// No message indicates that the message 
        }
        msg.target.dispatchMessage(msg);//消息分發(fā)
        msg.recycle();//回收消息
    }
}
    
###Message:
* 屬性target
發(fā)送消息時(shí)將消息的target屬性設(shè)置為this(就是Handler),在通過(guò)msg.target.dispatchMessage方法可以找到發(fā)送消息的Handler。
    
###MessageQueue:
*  1、獲取消息
    queue.next(),通過(guò)msg.when進(jìn)行計(jì)算出合適的Message.
    
    
###ActivityThread
    
Android程序入口函數(shù)是ActivityThread的main函數(shù),在這里先調(diào)用Looper.prepareMainLooper方法,創(chuàng)建ActivityThread.

final ApplicationThread mAppThread = new ApplicationThread();
private void attach(boolean system) {
if (!system) {
RuntimeInit.setApplicationObject(mAppThread.asBinder());
final IActivityManager mgr = ActivityManagerNative.getDefault();
mgr.attachApplication(mAppThread);
} else {
android.ddm.DdmHandleAppName.setAppName("system_process",
UserHandle.myUserId());
mInstrumentation = new Instrumentation();
ContextImpl context = ContextImpl.createAppContext(this,
getSystemContext().mPackageInfo);
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
}
}


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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容