如果在子線程中直接創(chuàng)建Handler并使用,如下代碼所示:
new Thread(){
@Override
public void run() {
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Toast.makeText(MainActivity.this, "handler msg", Toast.LENGTH_SHORT).show();
}
};
handler.sendEmptyMessage(0);
}
}.start();
此時(shí)運(yùn)行會(huì)報(bào)異常:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
原因分析:
非主線程默認(rèn)沒有創(chuàng)建Looper對(duì)象,也沒有沒有開啟消息循環(huán)寄啼。
解決方法:
- 直接獲取當(dāng)前子線程的looper
new Thread(){
@Override
public void run() {
Looper.prepare(); //獲取當(dāng)前線程的Looper涕刚,并prepare();
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Toast.makeText(MainActivity.this, "handler msg", Toast.LENGTH_SHORT).show();
}
};
handler.sendEmptyMessage(0);
Looper.loop(); //looper開始處理消息。
}
}.start();
- 獲取主線程的lopper
new Thread(){
@Override
public void run() {
Handler handler = new Handler(getMainLooper()) { //直接使用主線程的Looper
@Override
public void handleMessage(Message msg) {
Toast.makeText(MainActivity.this, "handler msg", Toast.LENGTH_SHORT).show();
}
};
handler.sendEmptyMessage(0);
}
}.start();