new Thread(new Runnable))。start()导致NetworkOnMainThreadException

时间:2013-11-01 21:45:15

标签: android sockets

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

大多数答案建议使用线程,不要在主线程中打开socket。

无论如何我的代码都是这样的

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

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

2 个答案:

答案 0 :(得分:1)

尝试在run()

中的for循环之前移动构造函数中的初始化代码

答案 1 :(得分:1)

在调用“new Client()”行时,你正在主线程中进行套接字调用,你应该在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的内容......

问候!