-
-
Save droidchief/4ff8d3454706cf3043f6e8ca551c0502 to your computer and use it in GitHub Desktop.
How to download file to Internal Storage in Android
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
//in async task | |
//usage | |
// DownloadVideoAsyncTask async = new DownloadVideoAsyncTask(this); | |
// async.execute("www.site.com/idvideo.mp4"); | |
public class DownloadVideoAsyncTask extends AsyncTask<String, Integer, String> { | |
private Context mContext; | |
public DownloadVideoAsyncTask(Context context) { | |
mContext = context; | |
} | |
@Override | |
protected void onPreExecute() { | |
super.onPreExecute(); | |
} | |
@Override | |
protected String doInBackground(String... sUrl) { | |
InputStream input = null; | |
OutputStream output = null; | |
HttpURLConnection connection = null; | |
try { | |
URL url = new URL(sUrl[0]); | |
connection = (HttpURLConnection) url.openConnection(); | |
connection.connect(); | |
// expect HTTP 200 OK, so we don't mistakenly save error report | |
// instead of the file | |
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { | |
return "Server returned HTTP " + connection.getResponseCode() | |
+ " " + connection.getResponseMessage(); | |
} | |
// this will be useful to display download percentage | |
// might be -1: server did not report the length | |
int fileLength = connection.getContentLength(); | |
// download the file | |
input = connection.getInputStream(); | |
// output = new FileOutputStream("/data/data/com.example.vadym.test1/textfile.txt"); | |
output = new FileOutputStream(mContext.getFilesDir() + "/file.mp4"); | |
byte data[] = new byte[4096]; | |
long total = 0; | |
int count; | |
while ((count = input.read(data)) != -1) { | |
// allow canceling with back button | |
if (isCancelled()) { | |
input.close(); | |
return null; | |
} | |
total += count; | |
// publishing the progress.... | |
if (fileLength > 0) // only if total length is known | |
publishProgress((int) (total * 100 / fileLength)); | |
output.write(data, 0, count); | |
} | |
} catch (Exception e) { | |
return e.toString(); | |
} finally { | |
try { | |
if (output != null) | |
output.close(); | |
if (input != null) | |
input.close(); | |
} catch (IOException ignored) { | |
} | |
if (connection != null) | |
connection.disconnect(); | |
} | |
return null; | |
} | |
@Override | |
protected void onProgressUpdate(Integer... values) { | |
super.onProgressUpdate(values); | |
Log.d("ptg", "onProgressUpdate: " + values[0]); | |
} | |
@Override | |
protected void onPostExecute(String s) { | |
super.onPostExecute(s); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment