I started creating file downloader class. Here is what i have:
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();
}
}
}
I need to call this downloader in new thread. Maybe someone could give me hint why i need to call new thread or asyc task for this.
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();
}
So when i want to downlaod my file it’s strating downloading asynchronical.
I don’t really want that.
I want to create downloader where i could choose if i want synchronously or async download a file.
But in the first place, i want to know when file was downloaded. How could i know this ?
Maybe someone had done this and could help me.
I need to know when file is downloaded.
Thanks.
You can’t download anything on the main thread, you get an Application Not Responding dialog in versions < 3.0, and in 3.0 and higher simply get an exception.
Your current approach is nearly right.
If you want to publish progress of downloading and notify UI about the finished downloading you can use AsyncTask, Handler or Intent to notify any application component about the finished downloading.