“NetworkOnMainThreadException”异常

来源:互联网 发布:经传证券炒股软件 编辑:程序博客网 时间:2024/05/19 13:22

“NetworkOnMainThreadException”异常

最近一不注意在主线程调用了带有Socket操作的函数,结果造成“NetworkOnMainThreadException”异常导致程序挂掉。android开发者网站中“NetworkOnMainThreadException”的解释:The exception that is thrown when an application attempts to perform a networking operation on its main thread.This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document Designing for Responsiveness.既然不允许在主线程中进行网络访问,那就创建一个子线程用来进行网络的操作

例如:

new Thread(new Runnable() {    @Override    public void run() {        try {            if(serverSocket!=null&&!serverSocket.isClosed()){                Socket socket = new Socket(serverAddress,serverPort);                }            }        } catch (IOException e) {            e.printStackTrace();        }    }}).start();
结果很成功。
原创粉丝点击