Created
April 7, 2014 20:15
-
-
Save nighthawk24/10043864 to your computer and use it in GitHub Desktop.
DownloadFile using AsyncTask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
new DownloadFile().execute(""); | |
private class DownloadFile extends AsyncTask<String, Void, String> { | |
protected String doInBackground(String... params) { | |
InputStream input = null; | |
OutputStream output = null; | |
HttpURLConnection connection = null; | |
try { | |
URL url = new URL("http://ftp.ee.debian.org/debian/ls-lR.gz"); | |
connection = (HttpURLConnection) url.openConnection(); | |
connection.setConnectTimeout(10000); | |
connection.setReadTimeout(10000); | |
connection.connect(); | |
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { | |
return "Server returned HTTP " + connection.getResponseCode() | |
+ " " + connection.getResponseMessage(); | |
} | |
// int fileLength = connection.getContentLength(); | |
input = connection.getInputStream(); | |
output = new FileOutputStream("/sdcard/file.zip"); | |
final byte buffer[] = new byte[16 * 1024]; | |
final InputStream inputStream = connection.getInputStream(); | |
int len1 = 0; | |
while ((len1 = inputStream.read(buffer)) > 0) { | |
Log.i("DPR", "doInBackground - downloading file"); | |
output.write(buffer, 0, len1); | |
} | |
} catch (Exception e) { | |
Log.i("DPR", "doInBackground - exception" + e.getMessage()); | |
return e.toString(); | |
} finally { | |
try { | |
if (output != null) | |
output.close(); | |
if (input != null) | |
input.close(); | |
connection.disconnect(); | |
} catch (IOException ignored) { | |
} | |
if (connection != null) | |
connection.disconnect(); | |
} | |
return null; | |
} | |
protected void onPostExecute(String result) { | |
} | |
protected void onPreExecute() { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment