我开始创建文件下载类。这是我有什么:异步文件下载器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();
}
因此,当我想要下载我的文件时,它会声明下载是异步的。
我真的不想那样。 我想创建一个下载器,我可以选择,如果我想要同步或异步下载文件。
但首先,我想知道文件何时被下载。我怎么知道这个?
也许有人这样做,可以帮助我。 我需要知道何时下载文件。
谢谢。
更好地发布解决方案,而不是稍后可能不再存在的链接。 – 2015-05-09 12:40:46