有時(shí)候在使用Thread和 handler 進(jìn)行線程操作的時(shí)候會(huì)發(fā)生 IllegalStateException么鹤,
錯(cuò)誤信息包含 IllegalStateException: Handler (android.os.Handler) {e8f132} sending message to a Handler on a dead thread
一般出現(xiàn)這種錯(cuò)誤意味著在 handler 進(jìn)行 postMessage / post 操作的時(shí)候,Lopper 中的 MessageQueue 隊(duì)列對(duì)象空了。
以下列舉一種發(fā)生這種問題可能的原因挚币。
example 1
HandlerThread thread = new HandlerThread(new String("TAG"));
Handler handler = new Handler(thread.getLooper());
//normal operation
handler.post(new Runnable(){
//do something
});
thread.quit();
if(thread.getState() == Thread.State.NEW) {
thread.start();
}
handler = new Handler(thread.getLooper());
//operation that will cause exception
handler.post(new Runnable() {
//do something
});
上面是一段會(huì)發(fā)生異常的代碼肩榕。
在 post 時(shí)會(huì)把 runnable 入隊(duì)列屹电,此時(shí)在 MessageQueue 的入隊(duì)操作會(huì)進(jìn)行判斷骤星,如果 mQuitting 為 true,則拋異常
image.png
基于以上原因,HandlerThread 在 quit 之后盡量不要再次使用
而是重新 new 一個(gè)出來
因?yàn)?HandlerThread 并沒有提供重新初始化的方法..也即是 quit 一次之后绘雁,MessageQueue 的 mQuitting 參數(shù)就永遠(yuǎn)為 true 了.. :-(