Netwok在Android 4.0的主线程异常 [英] Netwok on main thread exception in android 4.0

查看:91
本文介绍了Netwok在Android 4.0的主线程异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制定了工作正常的安卓4.0.0版本之前的应用程序。但在安卓4.0.0 +版本中,它越来越强制关闭。它说,网络上的主线程异常

I developed the app That is working fine in before android 4.0.0 versions. But in android 4.0.0 + versions it getting force close. It say network on main thread exception

推荐答案

为什么的Andr​​oid版本3.0 以上,你的应​​用程序崩溃,但能正常工作<$ C原因$ C>安卓2.X 是因为 蜂窝 冰淇淋三明治和< STRONG>果冻豆有更加严格的有关虐待的UI线程。例如,当运行蜂窝或以上的Andr​​oid设备检测到UI线程上的网络连接, NetworkOnMainThreadException 将抛出:

The reason why your application crashes on Android versions 3.0 and above, but works fine on Android 2.x is because HoneyComb Ice Cream Sandwich and Jelly Bean are much stricter about abuse against the UI Thread. For example, when an Android device running HoneyComb or above detects a network access on the UI thread, a NetworkOnMainThreadException will be thrown:

E/AndroidRuntime(673): java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example/com.example.ExampleActivity}:android.os.NetworkOnMainThreadException

的解释,为什么出现这种情况是有据可查的在Android开发者网站:

The explanation as to why this occurs is well documented on the Android developer's site:

A NetworkOnMainThreadException 被抛出。这只是抛出针对蜂窝SDK或更高版本的应用程序。针对早期SDK版本的应用程序可以做网络上的主要事件循环线程,但它严重阻碍。 该等操作的一些例子软糖 ICS 蜂窝和``不会让你在UI线程上执行的:

A NetworkOnMainThreadException is thrown when an application attempts to perform a networking operation on its main thread. This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. Some examples of other operations that JellyBean,ICSandHoneyComb and `` won't allow you to perform on the UI thread are:

  1. 打开一个Socket连接(即新的Socket())。
  2. 的HTTP请求(即了HTTPClient和HttpURLConnection类)。
  3. 试图连接到远程MySQL数据库。
  4. 下载文件(即Downloader.downloadFile())。
  1. Opening a Socket connection (i.e. new Socket()).
  2. HTTP requests (i.e. HTTPClient and HTTPUrlConnection).
  3. Attempting to connect to a remote MySQL database.
  4. Downloading a file (i.e. Downloader.downloadFile()).

如果您正试图执行任何UI线程对这些操作,则必须包装在一个工作线程。要做到这一点最简单的方法是使用的AsyncTask ,它允许你在你的用户界面执行异步工作。一个AsyncTask的将在辅助线程执行阻塞操作,并会公布在UI线程上的结果,而不需要自己处理的线程和/或处理程序。

If you are attempting to perform any of these operations on the UI thread, you must wrap them in a worker thread. The easiest way to do this is to use of an AsyncTask, which allows you to perform asynchronous work on your user interface. An AsyncTask will perform the blocking operations in a worker thread and will publish the results on the UI thread, without requiring you to handle threads and/or handlers yourself.

这篇关于Netwok在Android 4.0的主线程异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆