错误原因:android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
译文:android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程可以触摸其视图。
大家一看这个译文应该就能很块猜到是什么问题导致的了,下面看代码:
private void socketPorts(){
new Thread(new Runnable() {
@Override
public void run() {
try {
//创建客户端 第一个参数为地址,第二个参数为端口号
Socket socket = new Socket(host,post);
//获取输出流
OutputStream outputStream = socket.getOutputStream();
//转换为高级节点流
OutputStreamWriter writer = new OutputStreamWriter(outputStream);
//转换为缓冲流
BufferedWriter bufferedWriter = new BufferedWriter(writer);
//向服务器写入数据
bufferedWriter.write(masthed);
//刷新缓冲区
bufferedWriter.flush();
//获取输入流
InputStream inputStream = socket.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(reader);
//拼接字符串的类
StringBuffer buffer = new StringBuffer();
//用于保存获取到的数据
String line = "";
while ((line = bufferedReader.readLine()) != null) {
buffer.append(line);
Log.e("MainActivity",line);
}
showBsContent.setText(line);
//最后关闭socket
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
重点看红色字体的那段代码,这个Error就证明了一句话:在子线程中不能更新主线程的UI,否则会死的更惨!;
如果想在子线程中更新主线程的UI,我们可以采用Handler来处理,在子线程中发送消息给Handler,通知它更新UI;