国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Handler源碼分析

2019-11-09 17:27:56
字體:
來源:轉載
供稿:網友
每個Handler都關聯了一個線程,每個線程都維護了一個消息隊列MessageQueue,這樣Handler實際上就關聯了一個消息隊列。可以通過handler將message和runnable對象發送到該handler所關聯線程的messagequeue中,然后該消息隊列一直在循環拿出一個message,并對其處理。

當創建handler時,該handler就綁定了當前創建handler的線程。

一.在子線程使用Handler方式為:

Runnable runnable  = new Runnable(){

public void run(){

Looper.PRepare();

Handler handler = new Handler();

Looper.loop();

}

};

我們來分析一下,為什么要這么使用:

1. 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));    }它實例化了一個Looper,并且和當前線程綁定,也就是實例化一個Looper綁定到當前子線程。

2.Handler handler = new Handler();

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());            }        }        mLooper = Looper.myLooper();        if (mLooper == null) {            throw new RuntimeException(                "Can't create handler inside thread that has not called Looper.prepare()");        }        mQueue = mLooper.mQueue;        mCallback = callback;        mAsynchronous = async;    }這一段是實例化Handler。

3. Looper.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.recycle();        }    }我們可以發現for(;;)的死循環,queue.next()從MessageQueue隊列中取消息,

msg.target.dispatchMessage(msg); 其中msg.target一般是handler(下文會提到),然后由handler來分發消息。

 public void dispatchMessage(Message msg) {        if (msg.callback != null) {            handleCallback(msg);        } else {            if (mCallback != null) {                if (mCallback.handleMessage(msg)) {                    return;                }            }            handleMessage(msg);        }    }這里我看看到了熟悉的代碼handleMessage();先不看msg.callback和mCallback

當我們實例化handler,重寫handleMessage(),會在handlerMessage里面處理自己的邏輯(比如更新Ui等)

二:下面我們看看在UI線程使用handler的方式

Handler handler = new Handler();

handler.sendMessage();

這里有一個問題:為什么UI線程沒有調用 Looper.prepare()和Looper.loop();

帶著這個問題,我們來看看UI線程的源碼;

下面是ActivityThread的主函數入口:

public static void main(String[] args) {        SamplingProfilerIntegration.start();        // CloseGuard defaults to true and can be quite spammy.  We        // disable it here, but selectively enable it later (via        // StrictMode) on debug builds, but using DropBox, not logs.        CloseGuard.setEnabled(false);        Environment.initForCurrentUser();        // Set the reporter for event logging in libcore        EventLogger.setReporter(new EventLoggingReporter());        Security.addProvider(new AndroidKeyStoreProvider());        Process.setArgV0("<pre-initialized>");        Looper.prepareMainLooper();        ActivityThread thread = new ActivityThread();        thread.attach(false);        if (sMainThreadHandler == null) {            sMainThreadHandler = thread.getHandler();        }        AsyncTask.init();        if (false) {            Looper.myLooper().setMessageLogging(new                    LogPrinter(Log.DEBUG, "ActivityThread"));        }        Looper.loop();        throw new RuntimeException("Main thread loop unexpectedly exited");    }我們可以看到主線程已經創建了Looper,因此,在主線程使用handler時不需要Looper.prepare();

三 new Handler(Looper.getMainLooper()) 這種情況是,使用主線程的Looper

比如在子線程里面初始化handler,需要更新ui,那么就可以這么用。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 苍溪县| 扎鲁特旗| 花莲县| 侯马市| 青岛市| 孟州市| 榕江县| 嘉鱼县| 奉化市| 娱乐| 昌邑市| 浦县| 个旧市| 七台河市| 施甸县| 维西| 奉贤区| 临安市| 古丈县| 湘潭市| 滦平县| 香港 | 砚山县| 龙井市| 剑阁县| 祁门县| 通州市| 德昌县| 姜堰市| 道孚县| 土默特右旗| 张掖市| 宝坻区| 云安县| 城步| 灵璧县| 营口市| 包头市| 林口县| 南开区| 勐海县|