溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何解決使用Handler時(shí)Can't create handler inside thread that has not called Looper.prepare()問題

發(fā)布時(shí)間:2021-10-21 10:46:21 來源:億速云 閱讀:876 作者:小新 欄目:移動開發(fā)

這篇文章主要介紹了如何解決使用Handler時(shí)Can't create handler inside thread that has not called Looper.prepare()問題,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

    在android開發(fā)中,主線程不能進(jìn)行耗時(shí)操作,所以我們經(jīng)常把耗時(shí)操作放在子線程中進(jìn)行,那么就需要子線程與主線程相互交流,就需要使用到handler.

    而在使用handler過程中,如果對handler使用不太熟練的話就偶爾會出現(xiàn)Can't create handler inside thread that has not called Looper.prepare()的報(bào)錯(cuò)異常。之前在Handler的原理的博文中有講到,Handler的使用會依靠Looper循環(huán)來發(fā)送消息,如果不創(chuàng)建Looper對象,消息就無法發(fā)送,系統(tǒng)就會崩潰。那么為什么使用handler有時(shí)候可以運(yùn)行,有時(shí)候不能運(yùn)行呢?

    其實(shí)就是如果在主線程中創(chuàng)建handler時(shí),系統(tǒng)會自動創(chuàng)建Looper,但是在子線程中創(chuàng)建handler時(shí),是不會自動創(chuàng)建Looper的,此時(shí)如果不手動創(chuàng)建Looper,系統(tǒng)就會崩潰

    舉例如下:首先在子線程創(chuàng)建Handler(即主線程發(fā)送消息給子線程處理)

    如何解決使用Handler時(shí)Can't create handler inside thread that has not called Looper.prepare()問題

如何解決使用Handler時(shí)Can't create handler inside thread that has not called Looper.prepare()問題

系統(tǒng)就會報(bào)出Can't create handler inside thread that has not called Looper.prepare()的報(bào)錯(cuò)異常。

解決方法是:

如何解決使用Handler時(shí)Can't create handler inside thread that has not called Looper.prepare()問題

通過Looper.prepare();創(chuàng)建Looper對象

    下面在主線程中創(chuàng)建Handler

如何解決使用Handler時(shí)Can't create handler inside thread that has not called Looper.prepare()問題

在主線程創(chuàng)建Handler(即子線程發(fā)送消息給主線程處理),系統(tǒng)就會自動創(chuàng)建Looper,而不需要手動創(chuàng)建Looper.

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“如何解決使用Handler時(shí)Can't create handler inside thread that has not called Looper.prepare()問題”這篇文章對大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI