天天看點

Can't create handler inside thread that has not called Looper.prepare()

版權聲明:本文為部落客原創文章,轉載請标明出處。 https://blog.csdn.net/chaoyu168/article/details/52163029

最近做項目時出現個問題。

在一個基類中,建立一個Handler對象用于主線程向子線程發送資料,代碼如下:

this.mThirdHandler = new Handler(){
            @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());//isStop為基類中的一個私有成員
            };
        };           

但不知道為啥一直報錯: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,執行個體化基類時引入的一個參數。

繼續閱讀