Last active
September 11, 2024 23:55
-
-
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
This file contains hidden or 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
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(); | |
} | |
} | |
} |
@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
Can I use both OkHttp and DownloadManager (I want to show the download status at statusBar) for downloading videos programmatically?