简体   繁体   English

Android中的OS OS NetworkonMainThreadException错误

[英]android os networkonmainthreadexception error in android

I am getting the error "android.os.networkonmainthreadexception" while trying to pull a json data from an url. 尝试从网址中提取json数据时,出现错误“ android.os.networkonmainthreadexception”。 Would some tell me why? 有人告诉我为什么吗?

Its due to the StrictMode.ThreadPolicy. 其归因于StrictMode.ThreadPolicy。 It was introduced since API Level 9 and the default thread policy had been changed since API Level 11, which in short, does not allow network operation (eg: HttpClient and HttpUrlConnection) get executed on UI thread. 它是从API级别9开始引入的,并且自API级别11起已经更改了默认线程策略,简而言之,该策略不允许在UI线程上执行网络操作(例如:HttpClient和HttpUrlConnection)。 if you do this, you get NetworkOnMainThreadException. 如果执行此操作,则会收到NetworkOnMainThreadException。

The recommended way of solving this is by Using an AsyncTask so that the network request does not block the UI thread. 解决此问题的推荐方法是使用AsyncTask ,以使网络请求不会阻塞UI线程。

You can override this thread policy by adding the below code into your main activity's onCreate() method. 您可以通过将以下代码添加到主活动的onCreate()方法中来覆盖此线程策略。

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = 
        new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 中的Android.OS.NetworkOnMainThreadException - Android.OS.NetworkOnMainThreadException in Android asynctask json解析发生错误android.os.NetworkOnMainThreadException - Android asynctask json parsing getting error android.os.NetworkOnMainThreadException android.os.NetworkOnMainThreadException进入AsyncTask - android.os.NetworkOnMainThreadException into AsyncTask 改造 - android.os.NetworkOnMainThreadException - Retrofit - android.os.NetworkOnMainThreadException AsyncTask中的android.os.NetworkOnMainThreadException - android.os.NetworkOnMainThreadException in AsyncTask 错误:使用asynctask时出现android.os.NetworkOnMainThreadException - Error: android.os.NetworkOnMainThreadException while using asynctask ActionButton中的http连接android.os.NetworkOnMainThreadException错误 - Error in http connection android.os.NetworkOnMainThreadException in actionButton android.os.NetworkOnMainThreadException错误,即使在AsyncTask中运行 - android.os.NetworkOnMainThreadException error even when running in AsyncTask 我的JSON请求响应类中的android.os.networkonmainthreadexception错误 - android.os.networkonmainthreadexception error in my request response class for JSON android.os.NetworkOnMainThreadException在Android上使用rxjava - android.os.NetworkOnMainThreadException using rxjava on android
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM