最近做項目時出現個問題。
在一個基類中,創建一個Handler對象用於主線程向子線程發送數據,代碼如下
1 this.mThirdHandler = new Handler(){ 2 @Override 3 public void handleMessage(android.os.Message msg) { 4 super.handleMessage(msg); 5 Bundle bundle = msg.getData(); 6 isStop = bundle.getBoolean(mContext.getText(R.string.str_message_stop).toString());//isStop為基類中的一個私有成員 7 }; 8 };
但不知道為啥一直報錯:Can't create handler inside thread that has not called Looper.prepare()。
搜索后發現,原因是此Handler沒有Looper。到哪兒去找Looper呢?自己建?
在代碼前加入Looper.prepare();,心想這回可以了吧?
沒想到依然報錯,錯誤顯示,一個主進程只能有一個Looper,要死了。郁悶中...
突然我想到主進程中肯定有Looper,Context.getMainLooper(),再看Handler的實例化時是可以指定Looper的,太爽了,最后代碼如下
this.mThirdHandler = new Handler(mContext.getMainLooper()){ @Override public void handleMessage(android.os.Message msg) { super.handleMessage(msg); Bundle bundle = msg.getData(); isStop = bundle.getBoolean(mContext.getText(R.string.str_message_stop).toString()); }; };
mContext為主界面context,實例化基類時引入的一個參數。
希望以上的方法,可以給大家帶來點幫助。