【问题标题】:Code throws NetworkOnMainThread Exception despite being in another thread尽管在另一个线程中,代码仍会引发 NetworkOnMainThread 异常
【发布时间】:2020-01-14 13:50:14
【问题描述】:

我的应用程序中的一件事有问题。 当我在调试器中启动应用程序时,它会抛出一个错误 NetworkOnMainThreadException。 更具体地说,当在线程(非主线程)中连接到 Web 服务器时会引发异常 com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getResponseCode (HttpsURLConnectionImpl.java)。 因此,应用程序尝试在主线程上进行网络调用,但代码被另一个线程包围。

有问题的代码位于从 onResume 调用的 void 中。下面附上我的代码。

我已经尝试在另一个线程中包含整个代码,但仍然 - NetworkOnMainThread

final Runnable checker = new Runnable() {
    @Override
    public void run() {
        handler.removeCallbacks(null);
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL endpoint = new URL("###");
                    HttpsURLConnection conn =
                            (HttpsURLConnection) endpoint.openConnection(); //Here it throws mentioned Exception
                    if (conn.getResponseCode() == 200) {
                        InputStream response = conn.getInputStream();
                        String results = iStreamToString(response);
                        if(UserIdResults.equals("0")){
                            handler.postDelayed(this, 5000);
                        }else {
                            //Do Something
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }
};
handler.postDelayed(checker, 5000);

【问题讨论】:

    标签: java android android-studio mobile


    【解决方案1】:

    这个问题很可能是由这行引起的:

    handler.postDelayed(this, 5000);
    

    正如所写,this 指的是内部Runnable(您表示为闭包的那个)。这会导致您的网络执行 RunnableHandler 运行,当然,这是在主线程上。

    您可能打算运行checker,在这种情况下,您应该使用checker 代替this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      • 2016-04-24
      • 2020-05-08
      • 2015-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多