我遇到了一个尴尬的问题(可能对我来说)。我正在使用计时器来执行 Tcp 侦听器和套接字编程。我正在打开一个套接字以定期侦听从另一个 Android 设备(正常工作)发送的端口上存在的任何数据。我创建了 2 个应用程序来测试数据接收,一个只是虚拟的,第二个是我的主要应用程序。我在我的主应用程序中遇到异常,但在虚拟应用程序中没有。
例外是:android.os.NetworkonMainThreadException
两个应用程序中的代码完全相同
onCreate()
包含
timer2 = new Timer();
timer2.schedule(new TimerTask() {
@Override
public void run() {
TimerMethod();
}
}, 0, 1000);
TimerMethod()
如下
private void TimerMethod()
{
this.runOnUiThread(Timer_Tick);
}
Timer_Tick
是:
private Runnable Timer_Tick = new Runnable() {
public void run() {
try
{
runTcpServer();
}
catch(Exception a)
{
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(a.toString());
}
}
};
以及监听端口数据的主要tcp方法
public void runTcpServer()
{
ServerSocket ss = null;
try {
ss = new ServerSocket(TCP_SERVER_PORT);
//ss.setSoTimeout(10000);
//accept connections
Socket s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//receive a message
String incomingMsg = in.readLine() + System.getProperty("line.separator");
TextView tv= (TextView) findViewById(R.id.textView2);
//Log.d("TcpServer", "received: " + incomingMsg);
tv.append(incomingMsg);
//send a message
String outgoingMsg = "goodbye from port " + TCP_SERVER_PORT + System.getProperty("line.separator");
out.write(outgoingMsg);
out.flush();
Log.d("TcpServer", "sent: " + outgoingMsg);
//textDisplay.append("sent: " + outgoingMsg);
//SystemClock.sleep(5000);
s.close();
} catch (InterruptedIOException e) {
//if timeout occurs
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
Log.d("Error",e.toString());
}
}
}
}
我得到的例外是当我打电话runTcpServer()
给Timer_Tick