我一直试图让它工作一段时间。我正在尝试从手机向笔记本电脑上的简单服务器发送消息。我不断收到 NetworkOnMainThreadException,我尝试创建一个新线程(新 Runnable()等和一个 异步任务,但我仍然收到错误并且应用程序被强制关闭。我已经阅读了 3 或 4 个类似于这但没有一个对我有用。这是我的代码:
final Button post2 = (Button) findViewById(R.id.postbutton2);
post2.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new Thread(new Runnable() {
// TODO Auto-generated method stub
@Override
public void run() {
// TODO Auto-generated method stub
message = text.getText().toString(); //Message is a string, text is an EditText.
text.setText("");
try {
clientSocket = new Socket("10.0.0.2", 4445);
printWriter = new PrintWriter(clientSocket
.getOutputStream(), true);
printWriter.write(message);
printWriter.flush();
printWriter.close();
clientSocket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
Toast.makeText(context, e.toString(),
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, e.toString(),
Toast.LENGTH_SHORT).show();
}
}
}).start();
}
});