错误日志为:java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
例子如下:
new Thread(new Runnable() {
@Override
public void run() {
String path="http://192.168.0.101:8080/AndroidTest/mustLogin?logname="+name+"&password="+psw;
try {
try{
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(8000);
connection.setConnectTimeout(8000);
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String result = reader.readLine();
if (result.equals("login successfully!")){
Toast.makeText(MainActivity.this,"login successfully!",Toast.LENGTH_SHORT).show();
}
}catch (MalformedURLException e){}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
错误原因:
例子中在子线程弹Toast了,而Toast只能在UI线程弹出,需要修改。