2012-03-27 94 views
2

我开始创建文件下载类。这是我有什么:异步文件下载器android

public class Downloader { 

    //download url 
    URL url; 

    public Downloader(URL downloadURL){ 
     url = downloadURL; 
    } 


     public void toFile(File fName) { 
      try { 

       HttpURLConnection urlConnection = (HttpURLConnection) url 
         .openConnection(); 

       urlConnection.setRequestMethod("GET"); 
       urlConnection.setDoOutput(true); 

       urlConnection.connect(); 

       FileOutputStream fileOutput = new FileOutputStream(fName); 

       InputStream inputStream = urlConnection.getInputStream(); 

       byte[] buffer = new byte[1024]; 
       int bufferLength = 0; 

       while ((bufferLength = inputStream.read(buffer)) > 0) { 
        fileOutput.write(buffer, 0, bufferLength); 

       } 

       fileOutput.close(); 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 




} 

我需要在新线程中调用此下载程序。也许有人可以给我提示,为什么我需要为此调用新线程或asyc任务。

public void downloadFile(String urlToDownload,String path) throws MalformedURLException{ 




     new Thread(new Runnable() { 
      public void run() { 
       new Downloader(new URL(urlToDownload)).toFile(new File(path)); 

       } 


      }).start(); 
} 

因此,当我想要下载我的文件时,它会声明下载是异步的。

我真的不想那样。 我想创建一个下载器,我可以选择,如果我想要同步或异步下载文件。

但首先,我想知道文件何时被下载。我怎么知道这个?

也许有人这样做,可以帮助我。 我需要知道何时下载文件。

谢谢。

回答

4
  1. 你不能在主线程下载任何东西,你会得到一个应用程序在< 3.0版本没有响应对话框,并在3.0和更高版本简单地得到一个异常。

  2. 您目前的做法几乎是正确的。

  3. 如果要发布下载的进度,并通知UI关于完成下载,你可以使用AsyncTaskHandlerIntent通知任何应用程序组件对完成下载。

0

使用Handler知道您的文件何时被下载。

0

仍然使用AsyncTask,并使用onProgressUpdate方法。

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { 
    protected Long doInBackground(URL... urls) { 
     int count = urls.length; 
     long totalSize = 0; 
    for (int i = 0; i < count; i++) { 
     totalSize += Downloader.downloadFile(urls[i]); 
     publishProgress((int) ((i/(float) count) * 100)); 
    } 
    return totalSize; 
} 

protected void onProgressUpdate(Integer... progress) { 
    setProgressPercent(progress[0]); 
} 

protected void onPostExecute(Long result) { 
    showDialog("Downloaded " + result + " bytes"); 
} 

}

2
  1. 它启动的时候线程开始,以后你调用start()方法。为了方便平时使用Asyntask像matemink解决方案:

    +方法doInBackground()将在辅助线程运行

    +方法onPostExecute(0运行到更新UI线程

  2. 的关注:

    我需要在新线程中调用此下载程序。也许有人可以给 我暗示,为什么我需要调用新的线程或ASYC任务此

: 您需要下载单独的线程或Asyntask避免ANR对话框̣(如果您需要下载大文件或网络连接缓慢,可能导致主UI线程ANR对话框),这就是为什么你需要把工作线程,而不是主UI线程的高负载实现:

参考: http://developer.android.com/guide/practices/design/responsiveness.html

0

是的,你不能在主线程中执行网络操作。 您可以查看该存储库以下载文件。 AndroidFileDownloaderModule

+0

更好地发布解决方案,而不是稍后可能不再存在的链接。 – 2015-05-09 12:40:46