我使用它和StackoverFlow,但没有太多可用的信息。new Thread(new Runnable))start()会导致NetworkOnMainThreadException
而大多数答案建议使用线程,不要在主线程中打开套接字。
反正我这样的代码
public class Client implements Runnable {
private Socket socket;
private static ObjectOutputStream oos;
public Client() {
mPauseLock = new Object();
mPaused = false;
mFinished = false;
try {
socket = new Socket("168.131.148.50", 5001);
pw = new PrintWriter(socket.getOutputStream(), true);
oos = new ObjectOutputStream(socket.getOutputStream());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
for (int i = 0; i < MsgQueue.getSize(); i++) {
try {
oos.writeObject(MsgQueue.get(i));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
和MainActivity new Thread(new Client()).start();
但我仍得到NetworkOnMainThreadExcpetion ..
可有人告诉我的解决方案吗?