如何停止/取消下载文件?

时间:2013-10-29 20:59:48

标签: android

如何在下载时停止/取消文件? 即时通讯使用urlconnection和输入流。 代码工作但我不能取消它的下载。 我的下载代码:

            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.connect();
                int lenghtOfFile = conection.getContentLength();
                InputStream input = new                  BufferedInputStream(url.openStream(),8192);
                File myDir = getDir(Environment.DIRECTORY_MUSIC,
                        Context.MODE_PRIVATE);
                Intent i = getIntent();
                String name = i.getStringExtra("name");
                File mypath = new File(myDir, name + ".mp3");
                mypath.createNewFile();
                mypath.mkdirs();
                OutputStream output = new FileOutputStream(mypath);
                byte data[] = new byte[1024];
                long total = 0;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                    output.write(data, 0, count);
                }

                output.flush();

                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

1 个答案:

答案 0 :(得分:0)

一般的想法是使用一个定期检查的标志(可以从外部线程设置):

while (!cancelled && shouldDoStuff) { doStuff(); }

使用标志允许代码运行到正常完成(好,sorta),区分不同的"例外",并执行适当的清理操作。

现在, AsyncTask已经通过可以检查的标志提供了适当的取消机制

  

取消[AsyncTask]任务:可以随时通过调用cancel(boolean)取消任务。调用此方法将导致后续调用isCancelled()返回true。 ..为了确保尽快取消任务,您应该始终定期检查isCancelled()的返回值。

上面链接的文档中的修剪片段:

for (..) {                  // Keep going until done ..
  publishProgress(..);
  if (isCancelled()) break; // .. or until flagged.
}

(使用AsyncTask处理icky细节,比如正确实现所述标志,至少应为volatile。)

相关问题