Skip to content

Instantly share code, notes, and snippets.

@fnk0
Last active March 13, 2024 08:48
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save fnk0/51932c9ff5ec79f55c40 to your computer and use it in GitHub Desktop.
Save fnk0/51932c9ff5ec79f55c40 to your computer and use it in GitHub Desktop.
Example of how to download a video using Okhttp and show a progress bar to the user
class VideoDownloader extends AsyncTask<Void, Long, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Boolean doInBackground(Void... params) {
OkHttpClient client = new OkHttpClient();
String url = "http://myamazingvideo.mp4";
Call call = client.newCall(new Request.Builder().url(url).get().build());
try {
Response response = call.execute();
if (response.code() == 200 || response.code() == 201) {
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
Log.d(LOG_TAG, responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
InputStream inputStream = null;
try {
inputStream = response.body().byteStream();
byte[] buff = new byte[1024 * 4];
long downloaded = 0;
long target = response.body().contentLength();
mediaFile = new File(getActivity().getCacheDir(), "mySuperVideo.mp4");
OutputStream output = new FileOutputStream(mediaFile);
publishProgress(0L, target);
while (true) {
int readed = inputStream.read(buff);
if (readed == -1) {
break;
}
output.write(buff, 0, readed);
//write buff
downloaded += readed;
publishProgress(downloaded, target);
if (isCancelled()) {
return false;
}
}
output.flush();
output.close();
return downloaded == target;
} catch (IOException ignore) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
}
} else {
return false;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
@Override
protected void onProgressUpdate(Long... values) {
super.onProgressUpdate(values);
progressBar.setMax(values[1].intValue());
progressBar.setProgress(values[0].intValue());
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
progressBar.setVisibility(View.GONE);
if (mediaFile != null && mediaFile.exists()) {
playVideo();
}
}
}
@rockdevstack
Copy link

Can I use both OkHttp and DownloadManager (I want to show the download status at statusBar) for downloading videos programmatically?

@riyaz-ali
Copy link

@Ronacs You can use DownloadManager#addCompletedDownload() method and add the alredy downloaded file to the DownloadManager's database!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment