在多线程开发中,在Run方法中不能更新UI界面的控件,否则会报错: Can't create handler inside thread that has not called Looper.prepare():非主线程中默认没有创建Looper对象,需要先调用Looper.prepare()启用Looper。
解决方法一:使用Handler类操作;
方法二:在控件的代码的上方加上代码:Looper.prepare(),在控件代码下方加上代码:Looper.loop();
new Thread(){
@Override
public void run() {
HttpUtil httpUtil = new HttpUtil(url);
skey = httpUtil.getHttpMessage(name,password, token);
if (skey != null){
System.out.println(skey);
handler.sendMessage(handler.obtainMessage(10,skey));
}else{
Looper.prepare();
Toast.makeText(getApplicationContext(), R.string.toast3, Toast.LENGTH_LONG).show();
Looper.loop();
}
}
}.start();
如:想要更新蓝色字体的Toast控件,就要加上红色字体的代码。