在更改活动时停止异步任务中的 HTTP 请求

发布于 2024-12-25 06:02:09 字数 255 浏览 0 评论 0原文

我正在一个活动中下载多个图像以填充列表视图,所有这些都在单独的异步任务中。在此活动中,用户可以按按钮转到不需要图像的另一个页面。

我遇到的问题是,即使进入下一个活动,异步任务仍在运行,并且不会为下一个活动中需要发出的请求释放 httpclient。

我尝试对所有正在运行的任务使用 asynctask.cancel,但这会引发 InterruptedIOException。

是否有其他优雅的方式来停止正在发出的请求以释放客户端?

I am downloading multiple images in an activity to populate a list view, all in seperate async tasks. In this activity the user can press a button to go to another page which doesn't require the images.

The issue I run into is that even on going to the next activity the async tasks are still running and the httpclient isn't released for the requests that need to be made in this next activity.

I tried using asynctask.cancel for all the tasks running, but that throws an interruptedIOException.

Is there any other graceful way of stopping the requests that are being made to free up the client?

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

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

发布评论

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

评论(1

关于从前 2025-01-01 06:02:09

理想情况下,在这种情况下您想要做的是将 HTTP 请求包装在可以取消的循环中。使用这个问题作为示例(那里有完整的实现):

@Override
protected Void doInBackground(Void... params) {
  while (running) {
    // loop your HTTP requests here
  }
  return null;
}

当您触发onCancelled()时方法(通过调用 cancel),您的 doInBackground 方法将在当前 HTTP 请求完成后尽快终止(并且不会之前)。

这可能是使用 AsyncTask 获得的最优雅的解决方案。另外,您可能必须在 AsyncTask 类中的某个位置捕获中断的异常,但这应该足以让您继续下去。

Ideally, what you want to do in these kinds of situations is to wrap your HTTP requests in a loop that can be cancelled. Using this question as an example (full implementation there):

@Override
protected Void doInBackground(Void... params) {
  while (running) {
    // loop your HTTP requests here
  }
  return null;
}

When you trigger the onCancelled() method (by calling cancel), your doInBackground method will terminate as soon as the current HTTP request is complete (and not before).

This is likely to be the most graceful solution you're going to get using AsyncTask. Also, you might have to catch the interrupted exception somewhere in your AsyncTask class, but this should be enough to get you going.

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