【发布时间】: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