(Android) 线程化 httpClient 任务,不阻塞 UI?

发布于 2024-11-10 05:54:45 字数 365 浏览 4 评论 0原文

我制作了一个应用程序,根据用户输入从互联网获取网页,该应用程序有效。获取分为不同的步骤:使用来自 edittext 的字符串作为参数进行发布,经过一些解析后,返回一个名称数组,这些名称将显示在 AlertDialog 中。当用户选择一个时,它会使用该字符串作为参数发布另一篇文章。
这可行,但现在我想将其设为线程化(或类似),以便 UI 不会变得无响应。 我尝试了 Threads、Runnables 和 AsyncTask,但我就是找不到一种结构来在单个线程中获取数据,并且还能够返回该数组并选择一个名称,而无需创建 HttpClient 的新实例。这会删除你看到的 Cookie...

我花了大约整整一周的时间来解决这个问题,但只是没有看到它:(

所以有人有想法吗?谢谢!

I've made an application that Fetches a Webpage from the internet, based on user input, wich worked. The fetching goes in different steps: post with String from edittext as parameter, after some parsing this returns an Array of names wich are displayed in an AlertDialog. When the user picks one, it makes another post with that String as parameter.
This works, but now I want to make it Threaded (or similar), so that the UI doesn't get unresponsive.
I tried Threads, Runnables and AsyncTask, but I just cannot find out a construction to get the fetching in a single Thread, and also be able to return that array and pick a name, WITHOUT making a new instance of my HttpClient. This would erase Cookies you see...

I've spent about a whole week to figuring this out, but just don't see it :(

So anyone got an idea? thanks !

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

还给你自由 2024-11-17 05:54:45

对于每一次 HTTP 访问,您都可以创建一个单独的 AsyncTask 子类,然后依次实例化它们中的每一个,并执行它们。网上有很多关于如何使用 AsyncTask 访问 HTTP 的示例,例如 此处此处(仅谷歌搜索类似的东西 这个)。

此处要掌握的主要思想是在 AsyncTask 的 doInBackground 方法体内执行所有与网络相关的操作。

正如 Ted Hopp 所说,您可以让 HttpClient 实例成为 Activity 的私有成员(或者任何持有两个 AsyncTask 的类),以便第一个 AsyncTask 将创建它,而第二个 AsyncTask 可以创建它。使用相同的。

For each of your HTTP accesses, you can create a separate AsyncTask subclass, then instantiate each one of them in turn, and execute them. On the web there are many examples on how to use AsyncTask to access HTTP, e.g. here or here (just google for something like this).

The main idea to grasp there, is to do all the network-related operations inside the doInBackground method body of the AsyncTask.

As Ted Hopp said, you can let the HttpClient instance be a private member of your Activity (or whatever class holds the two AsyncTasks), so that the first AsyncTask will create it, and the second one can just use the same.

柏拉图鍀咏恒 2024-11-17 05:54:45

您可以使用两个 AsyncTask 子类,每个请求一个。授予子类访问活动类中存储 HttpClient 对象的变量的权限。

You can use two AsyncTask subclasses, one for each request. Give the subclasses access to a variable in your activity class that stores the HttpClient object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文