使用 httpclient 和 asynctask 取消文件下载 [英] Cancelling file download with httpclient and asynctask
问题描述
在我的应用程序中,我需要从 url 位置下载文件.我想在对话框中(或可选地在通知区域中)显示下载进度.我在这个主题上遇到了几个很好的资源(比如 http://progrnotes.blogspot.com/2010/09/c-android.html).不幸的是,所有示例都没有明确说明如何根据用户请求正确取消下载.所以我的问题其实很简单:
In my app I need to download files from url locations. I want to display progress of the download in a dialogbox (or optionally in the notification area). I've come across several good resources on this subject (something like http://progrnotes.blogspot.com/2010/09/c-android.html). Unfortunately, all the examples don't provide a clear indication on how to properly cancel a download per the user's request. So my question is actually quite simple:
给定一个异步任务,它在后台下载文件(使用 httpclient)并显示一个带有下载进度和取消按钮的对话框,我如何在按下按钮时取消下载并停止后台任务?
Given an asynctask which downloads the file in the background (with httpclient) and displays a dialogbox with download progress and a cancel button, how do I can cancel the download and stop the background task when the button is pressed?
我知道终止线程通常不是一个好主意,因此我可能需要在后台线程中使用取消"变量.如何将按钮的停止信号传递给异步任务?
I know killing threads is generally not a good idea, so I will probably need to work with a 'cancel'-variable in my background thread. How do I communicate a stop signal from the button to the asynctask?
问候,伊沃
推荐答案
让你的按钮调用 AsyncTask.cancel(true)
然后从内部检查 isCancelled()
代码>doInBackground(Params... params).通过这种方式,您可以通知后台线程应该取消下载,并且您可以采取适当的步骤来停止下载.
Have your button call AsyncTask.cancel(true)
and then check isCancelled()
from inside doInBackground(Params... params)
. In this manner, you can communicate to the background thread that the download should be cancelled, and you can take the appropriate steps to stop it.
这篇关于使用 httpclient 和 asynctask 取消文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!