0

我目前正在编写和 android 应用程序,我正在使用 HttpClients 和那些类。我花了 2 个小时试图修复一些错误,直到我读到一篇文章说你不能在主线程中执行该操作。所以他们建议我使用 AsyncTask。

所以我的问题是,我怎么知道应该在不同的线程中完成哪些操作?有我可以阅读它们的列表吗?

任何信息都会很好,在此先感谢。

4

5 回答 5

3

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 ICS and HoneyComb won't allow you to perform on the UI thread are:

  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()).

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.

于 2013-03-30T21:13:53.413 回答
2

网络异常是唯一会通过阻塞 UI 线程在 android 中抛出的异常。因此,您必须通过在 android 中编程牢记 3 条规则。

不要让 UI-Thread 处理需要超过 5 秒才能完成的操作。

不要让广播接收器处理需要超过 20 秒才能完成 onReceive() 的操作。

并且不要在 UI-Thread 中处理网络操作。

于 2013-03-30T21:06:58.847 回答
1

正如其他答案所说,Android不是线程安全的,这意味着:

  • 您不能从后台线程操作 UI
  • 您不能在 UI 线程上执行繁重的任务

其他此类操作可能包括处理大量数据/数据库操作/HTTP 请求/网络管理。真的,我相信任何不需要 UI 线程但确实涉及大量处理时间的东西都应该移到单独的线程中。

这是合乎逻辑的,因为如果您要进行繁重的处理,用户会感到延迟并且用户体验会受到影响(当然,肯定会被用来使系统过载等)因此,系统会杀死处理并在蜂窝后抛出错误。

因此,您想要使用异步任务。

异步任务实际上只是打开了一个新线程,您可以在该线程上执行繁重的处理或网络连接。对于网络连接,我建议使用像这样的 AsyncClients,它以一种更容易使用的格式实现 AsyncTask。还有像UniversalImageLoader这样的库,可以让您将图像加载到网格/列表中。

我还强烈建议您阅读讨论此问题的官方 Android 文档,并且在 Android 博客上也有一篇有用的帖子。最后,我觉得这篇文章可能对您有用,因为它可能包含您遇到的错误(错误,因为您在 UI 线程上执行了操作)。

我发现的其他资源:

总之,这是一个使用 AsyncTask 的示例。(很好地回答了@Graham Smith)。

于 2013-03-30T21:09:14.480 回答
0

任何需要花费大量时间的事情都应该在另一个线程中完成。这包括大型 IO 和网络访问。但是我认为只有网络访问会引发异常,其他任何事情都会导致 UI 无响应。尽管如果您花费的时间太长,您将触发看门狗计时器并且该应用程序将被杀死。

于 2013-03-30T20:53:55.597 回答
0

正如 Gabe 所提到的,您应该在单独的线程中执行繁重的任务。

关于 android 线程有两件重要的事情。

1是通用线程..(按照您的要求做的线程)

2是ui线程...(监听用户反应并绘制ui的线程)

您只能通过 ui 线程更改 ui(Views act)。

另一方面,在蜂窝之后,禁止在主线程中进行 http 请求。(称为严格模式)

简而言之,任何阻止用户交互的操作都应该在另一个线程中完成。

我希望这可以帮助你。

于 2013-03-30T21:04:37.650 回答