[英]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.