gpt4 book ai didi

android - 取消 HTTP 下载程序 AsyncTask 的最佳方法

转载 作者:搜寻专家 更新时间:2023-11-01 08:46:43 27 4
gpt4 key购买 nike

我有一些 AsyncTasks 从网络下载数据。如果在某个时候我需要阻止它们,最好的方法是什么?
有关文档:

task.cancel(mayInterruptIfRunning)

说:

Attempts to cancel execution of this task. This attempt will fail if the task has already completed, already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.

Calling this method will result in onCancelled(Object) being invoked on the UI thread after doInBackground(Object[]) returns. Calling this method guarantees that onPostExecute(Object) is never invoked. After invoking this method, you should check the value returned by isCancelled() periodically from doInBackground(Object[]) to finish the task as early as possible.

据我了解,如果 mayInterruptIfRunning=true 它会尝试中断线程,但如果它不成功,则必须在后台流上连续检查 isCancelled()。
这是 HTTP 案例。我在某处读到 Thread.interrupt 实际上并没有中断 IO 操作,但是 cancel() 失败就是这种情况。
因此如何中止下载?

这里我想到了一些可能性:

  1. 使用 ApacheHttp*:重写 cancel(boolean) 方法并调用新的 cancel(.),例如 httpUriRequestInstance.abort()
  2. 使用 HttpURLConnection:我可以获得输入流并在一段时间内填充另一个缓冲输出流,以便定期检查与 isCancelled() 关联的标志。我的意思是:

    ... httpURLConnection code which creates an HttpURLConnection "conn"  
    InputStream in = conn.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream(defSize);
    byte[] buff = new byte[buffSize];
    int br;
    while( (br = in.read(buff) ) >-1){
    if(cancelled) return null; //eventually closing th inpustream
    baos.write(buffer,0,br);
    }
    // ...

你有什么建议?

最佳答案

我肯定会选择 HttpURLConnection。并且可能会做类似的事情:

  1. 将 public void cancel() 方法添加到我的自定义 AsyncTask实现
  2. cancel() 实现为

    public void cancel() {
    这个。取消(真);
    mConnection.disconnect();
    //TODO 尝试关闭输入流
    }

  3. 在需要时从我的 Activity 调用 mMyAsyncTask.cancel()

关于android - 取消 HTTP 下载程序 AsyncTask 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27565007/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com