TCP 客户端套接字不适用于 api19
TCP client socket doesn't work on api19
当我在 HTC Wildfire S(API10,android 2.3.3)中使用我的代码时,它工作正常。但是如果我在 Samsung Galaxy S4(API19,android 4.4.2)上 运行,它就不起作用(应用程序启动和关闭;没有任何反应)。服务器在我的本地计算机上(Hercules 程序)。当然,我在清单中添加了权限(互联网)。
密码是:
try{
Socket s = new Socket("192.168.1.13", 6914);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String outMsg = "";
outMsg = "This is Client";
out.write(outMsg);
out.flush();
out.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
那么你能帮我看看问题出在哪里吗?我没有 root 我的三星 phone。
您似乎是主 (UI) 线程中的 运行 网络相关代码。在 Android 1.x 和 2.x 上,不推荐这样做,因为它可能导致 UI 冻结。由于 Android 3.x(并且在 Android 4.x 和 5.0 中仍然有效),现在已被平台严格禁止。如果您有机会阅读日志,您将获得 NoNetworkInMainThreadException
。
要实现这种测试,我建议您使用 Thread
:
new Thread() {
public void run() {
// Your network code, it will run on another thread
}
}.start();
如果您需要在主线程上返回结果(您可能在某些时候需要),您将需要查看更复杂的模式,例如 AsyncTask
。
当我在 HTC Wildfire S(API10,android 2.3.3)中使用我的代码时,它工作正常。但是如果我在 Samsung Galaxy S4(API19,android 4.4.2)上 运行,它就不起作用(应用程序启动和关闭;没有任何反应)。服务器在我的本地计算机上(Hercules 程序)。当然,我在清单中添加了权限(互联网)。
密码是:
try{
Socket s = new Socket("192.168.1.13", 6914);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String outMsg = "";
outMsg = "This is Client";
out.write(outMsg);
out.flush();
out.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
那么你能帮我看看问题出在哪里吗?我没有 root 我的三星 phone。
您似乎是主 (UI) 线程中的 运行 网络相关代码。在 Android 1.x 和 2.x 上,不推荐这样做,因为它可能导致 UI 冻结。由于 Android 3.x(并且在 Android 4.x 和 5.0 中仍然有效),现在已被平台严格禁止。如果您有机会阅读日志,您将获得 NoNetworkInMainThreadException
。
要实现这种测试,我建议您使用 Thread
:
new Thread() {
public void run() {
// Your network code, it will run on another thread
}
}.start();
如果您需要在主线程上返回结果(您可能在某些时候需要),您将需要查看更复杂的模式,例如 AsyncTask
。