Can't create handler inside thread that has not called Looper.prepare()
问题描述:
开启一个子线程,使用handler去提醒ui线程,使用了Toast。贴出代码来
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// super.handleMessage(msg);
switch (msg.what) {
case StrUtil.FORGET_PWD_SUCCEED:
// dismissDialog();
Toast.makeText(PasswordBackActivity.this,"密码成功找回",Toast.LENGTH_SHORT).show();
break;
case StrUtil.FORGET_PWD_FAILED:
dismissDialog();
Toast.makeText(PasswordBackActivity.this,"网络错误,密码未找回",Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
};
出现错误的地方很奇怪,是
Toast.makeText(PasswordBackActivity.this,"密码成功找回",Toast.LENGTH_SHORT).show();
而下面一行
Toast.makeText(PasswordBackActivity.this,"网络错误,密码未找回",Toast.LENGTH_SHORT).show();
却不会出错。只有上面的会出错,下面的正常运行。
不知道是怎么回事,但我的解决方法是:
......
......
message.what = StrUtil.FORGET_PWD_SUCCEED;
handler.handleMessage(message);
Looper.prepare();
Toast.makeText(PasswordBackActivity.this,"密码成功找回",Toast.LENGTH_SHORT).show();
Looper.loop();
......
......
将Toast移到子线程中,并且在Toast上下使用Looper包括起来。
Looper.prepare();
Looper.loop();
问题解决,没报错