安卓停止下载

发布于 2024-10-16 00:55:40 字数 792 浏览 2 评论 0原文

在我的应用程序中,我下载并解析一个 html 页面。但是,我希望能够停止下载(即当用户点击取消时)。

这是我现在使用的代码,它是从 ASyncTask 的 doInBackground 调用的。

如何从 ASyncTask 外部取消此请求?

我目前使用 htmlcleaner

   HtmlCleaner cleaner = new HtmlCleaner();
   CleanerProperties props = cleaner.getProperties();
   props.setAllowHtmlInsideAttributes(true);
   props.setAllowMultiWordAttributes(true);
   props.setRecognizeUnicodeChars(true);
   props.setOmitComments(true);
   try {
        URL url = new URL(urlstring);
        URLConnection conn = url.openConnection();
        TagNode node = cleaner.clean(new InputStreamReader(conn.getInputStream()));
        return node;
   } catch (Exception e) {
       failed = true;
       return;
   }

In my application I download and parse a html page. However, I want to be able to stop the download in its tracks (i.e. when the user hits cancel).

This is the code I use now, which is being called from doInBackground from ASyncTask.

How do I cancel this request from outside of the ASyncTask?

I currently use htmlcleaner

   HtmlCleaner cleaner = new HtmlCleaner();
   CleanerProperties props = cleaner.getProperties();
   props.setAllowHtmlInsideAttributes(true);
   props.setAllowMultiWordAttributes(true);
   props.setRecognizeUnicodeChars(true);
   props.setOmitComments(true);
   try {
        URL url = new URL(urlstring);
        URLConnection conn = url.openConnection();
        TagNode node = cleaner.clean(new InputStreamReader(conn.getInputStream()));
        return node;
   } catch (Exception e) {
       failed = true;
       return;
   }

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

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

发布评论

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

评论(2

野心澎湃 2024-10-23 00:55:40

你不能使用AsyncTask.cancel()吗?然后您应该能够使用 onCancelled 回调返回到主活动。

Can't you use AsyncTask.cancel()? You should be able to then use the onCancelled callback to return to the main activity..

追风人 2024-10-23 00:55:40

好吧,我相信我已经解决了这个问题。

在我的 Activity 类中,我有一个变量(布尔值)failed。另外,我在活动中有一个私有的 Downloader 类,它扩展了 ASyncTask。这样,Downloader 类就可以访问 failed 布尔值。当 Activity 启动时,它会启动 Downloader 任务并弹出一个进度对话框。任务完成后,它会关闭对话框,然后继续处理下载的内容。

但是,当用户取消进度对话框时,failed 设置为 true,并且通过调用 finished 将用户发送回上一个活动。与此同时,Downloader 仍在忙于下载。因为现在结果是不必要的,我们希望它尽快停止使用资源。为了实现这一目标,我将 doInBackground 方法分解为尽可能多的步骤。在每个步骤之后,我都会检查 failed 是否仍为 false,当它设置为 true 时,它根本不会进入下一步。请参阅下面的实际操作。此外,BufferedReader reader 是公共的,并且在 onCancelled 方法中我执行 reader.close() 。这会抛出各种异常,但这些异常都会被正确捕获。

 public void DoInBackground(.........) {
    try {
        URL url = new URL(uri);
        URLConnection conn = url.openConnection();
        if (!failed) {
            isr = new InputStreamReader(conn.getInputStream());
            if (!failed) {
                reader = new BufferedReader(isr);
                publishProgress(1);
                if (!failed) {
                    TagNode node = cleaner.clean(reader);
                    publishProgress(2);
                    return node;
                }
            }
        }
     } catch (Exception e) {
          failed = true;
          Log.v("error",""+e);
     } 
 }

@Override
protected void onCancelled() {
    failed = true;
    if (reader != null)
        try {
            reader.close();
        } catch (IOException e) {
            failed = true;
        }
    if (isr != null)
        try {
            isr.close();
        } catch (IOException e) {
        }
}

我知道我可以将下载过程分解为更小的部分,但我下载的文件非常小,所以这并不重要。

Ok, I believe I've solved this.

In my Activity class I have a variable (boolean) failed. Also, I have a private Downloader class within the activity which extends ASyncTask. This way, the Downloader class has access to the failed boolean. When the Activity launches, it starts the Downloader task and a progress dialog pops up. When the task finishes, it closes the dialog and then goes on processing the downloaded content.

However, when the user cancels the progress dialog, failed is set to true, and the user is sent back to the previous activity by a call to finished. In the meantime, Downloader is still busy downloading. Because the results are now unneccessary, we want it to stop using resources asap. In order to accomplish this, I have broken up the doInBackground method in as much steps as possible. After each step I check if failed is still false, when it is set to true, it simply doesn't go to the next step. See it in action below. Furthemore, the BufferedReader reader is public, and in the onCancelled method I execute reader.close(). This will throw all sorts of exceptions, but these are properly caught.

 public void DoInBackground(.........) {
    try {
        URL url = new URL(uri);
        URLConnection conn = url.openConnection();
        if (!failed) {
            isr = new InputStreamReader(conn.getInputStream());
            if (!failed) {
                reader = new BufferedReader(isr);
                publishProgress(1);
                if (!failed) {
                    TagNode node = cleaner.clean(reader);
                    publishProgress(2);
                    return node;
                }
            }
        }
     } catch (Exception e) {
          failed = true;
          Log.v("error",""+e);
     } 
 }

@Override
protected void onCancelled() {
    failed = true;
    if (reader != null)
        try {
            reader.close();
        } catch (IOException e) {
            failed = true;
        }
    if (isr != null)
        try {
            isr.close();
        } catch (IOException e) {
        }
}

I know that I could have broken up the downloading process in even tinier bits, but I am downloading very small files, so it's not that important.

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