我正在尝试为 Android 编写一个简单的聊天应用程序,所以我有一个聊天服务器,我正在尝试连接到它。所以在我的主要课程中
final EditText etHost = (EditText) findViewById(R.id.entry1);
final EditText etPort = (EditText) findViewById(R.id.entry2);
final EditText messageBoard = (EditText) findViewById(R.id.editText1);
final EditText etSend = (EditText) findViewById(R.id.editText2);
soEd = new SocketAndEditText(etHost, etPort, messageBoard, etSend);
SetNetworking net = new SetNetworking();
SocketAndEditText net.execute(soEd);
final Button sendButton = (Button) findViewById(R.id.button2);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Messager mes = new Messager();
mes.execute(soEd);
}
});
SocketAndEditText
是一个我只保留套接字和四个EditText
组件的类。这个想法是SetNetworking
建立网络连接并Messager
发送消息。两个类都实现AsyncTask
:
public class SetNetworking extends AsyncTask<SocketAndEditText, Void, Void> {
...
public class Messager extends AsyncTask<SocketAndEditText, Void, Void> {
...
但奇怪的是onPostExecute(Void result)
,Messager
当我尝试做一件非常简单的事情时
try {
InetAddress address1 = InetAddress.getByName("130.237.161.23");
boolean reachable = address1.isReachable(4456);
messageBoard.setText("Is host reachable?" + reachable);
} catch (Exception e) {
messageBoard.setText("Test not working! " + e.toString());
}
我明白了:
测试不工作!android.os.NetworkOnMainThreadException
为什么因为它在 AsyncTask 中而不是在主线程中?