0

我用谷歌搜索了它和 StackoverFlow,但我可以使用的信息不多。

而且大多数答案都建议使用线程,不要在主线程中打开套接字。

反正我的代码是这样的

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 ..

有人可以告诉我解决方案吗?

4

2 回答 2

1

尝试在 run() 中的 for 循环之前移动构造函数中的初始化代码

于 2013-11-01T21:47:23.207 回答
1

调用“new Client()”这一行时,你是在主线程中进行socket调用,你应该把所有与socket创建相关的代码移到run方法里面,你要知道只有“run”方法在里面执行后台线程,而不是类初始化:

public class Client implements Runnable {
private Socket socket;

private static ObjectOutputStream oos;

public Client() {
    mPauseLock = new Object();
    mPaused = false;
    mFinished = false;
}

public void run() {
    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();
    }


    for (int i = 0; i < MsgQueue.getSize(); i++) {
        try {
            oos.writeObject(MsgQueue.get(i));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

在进入 Android 之前,您应该阅读有关 java 的更多信息......

问候!

于 2013-11-01T21:49:00.947 回答