【问题标题】:Why do I get an exception during wifi direct socket connection? [duplicate]为什么在 wifi 直接套接字连接期间出现异常? [复制]
【发布时间】:2014-12-02 18:31:55
【问题描述】:

当我在我的 android 服务器设备上运行该代码时出现异常,但我不明白为什么,请您帮帮我。

WifiP2pDevice peer = wifiP2pDeviceList.getDeviceList().iterator().next();
String host = peer.deviceAddress;
ServerSocket serverSocket = new ServerSocket(2009);
Socket client = serverSocket.accept(); // I got the exception here

例外: 致命例外:主要 android.os.NetworkOnMainThreadException

【问题讨论】:

    标签: android sockets android-wifi serversocket wifi-direct


    【解决方案1】:

    Android 将网络调用识别为可能没有响应,因此它会阻止您在 UI 线程上执行此操作。您需要在AsyncTask 或后台进程中拨打电话。看到这个:

    http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

    以及对错误的附加(流行)解释:

    How to fix android.os.NetworkOnMainThreadException?

    【讨论】:

      【解决方案2】:

      这是因为在 UI 线程中不允许使用与网络相关的内容,但有一种解决方法,只需在您的 onCreate 中的 setContentView 下方添加这些行(以避免任何错误:))

      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);
      

      但是,如果您在非 UI 线程上执行此操作,那将是一个好习惯。

      【讨论】:

        猜你喜欢
        • 2013-04-24
        • 1970-01-01
        • 2018-05-26
        • 1970-01-01
        • 2014-03-01
        • 1970-01-01
        • 2021-06-01
        • 2014-09-18
        • 1970-01-01
        相关资源
        最近更新 更多