how to download video from url in android programmatically
AndroidManifest.xml
<!--- Add Internet Permissions in the Manifest File-->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- Add Read and Write Permissions in the Manifest File-->
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/downloadBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Download File" />
</LinearLayout>
MainActivity.java
import android.Manifest;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.core.content.ContextCompat;
import java.io.File;
public class MainActivity extends AppCompatActivity {
private String fileUrl = "https://jsoncompare.org/LearningContainer/SampleFiles/Video/MP4/sample-mp4-file.mp4";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final AppCompatButton downloadFile = findViewById(R.id.downloadBtn);
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setCancelable(false);
downloadFile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// check if external storage permissions granted or not
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
// request for permissions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 102);
}
} else {
// show progress dialog
progressDialog.show();
// download file
DownloadFile.download(MainActivity.this, fileUrl, "fileNamedataa.mp4", new DownloadProgressListener() {
@Override
public void progress(int downloaded, int totalFileSize) {
// creating downloaded percentages
int percentages = (downloaded * 100) / totalFileSize;
// setting progress to ProgressDialog
progressDialog.setMessage("Downloaded = " + percentages + "%");
}
@Override
public void success(File downloadedFile) {
}
@Override
public void error(String errorMessage) {
}
});
}
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 102) {
if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permissions Declined", Toast.LENGTH_SHORT).show();
}
}
}
}
DownloadFile.java
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadFile {
private static DownloadProgressListener downloadProgressListener;
public static void download(Context context, String fileUrl, String fileName, DownloadProgressListener downloadProgressListener) {
new Thread(new Runnable() {
@Override
public void run() {
DownloadFile.downloadProgressListener = downloadProgressListener;
try {
// Create Url
URL url = new URL(fileUrl);
// Making HTTP Request
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
// getting file length
int fileSize = connection.getContentLength();
// getting input stream
InputStream inputStream = connection.getInputStream();
// creating byte buffer to read bytes from InputStream
byte[] buffer = new byte[1024];
// to store total downloaded bytes
int totalDownloadedBytes = 0;
// for below API level 29 we need to use old way to store Media Files like images, videos, etc.
final String picturesDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).toString();
File destinationFile = new File(picturesDirectory, fileName);
OutputStream outputStream;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentValues values = new ContentValues();
values.put(MediaStore.Video.Media.DISPLAY_NAME, fileName); // set image filename
values.put(MediaStore.Video.Media.RELATIVE_PATH, Environment.DIRECTORY_MOVIES);
// creating file
Uri fileUri = context.getContentResolver().insert(MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY), values);
outputStream = context.getContentResolver().openOutputStream(fileUri);
} else {
outputStream = new FileOutputStream(destinationFile);
}
while (true) {
// getting bytes / download bytes
int downloadedBytes = inputStream.read(buffer);
// -1 means all the bytes has downloaded successfully
if (downloadedBytes == -1) {
Looper.prepare();
DownloadFile.downloadProgressListener.success(destinationFile);
// close outputStream and inputStream
outputStream.close();
inputStream.close();
// break the loop
break;
} else {
// writing output stream
outputStream.write(buffer, 0, downloadedBytes);
// append downloadedBytes to totalDownloadedBytes
totalDownloadedBytes = totalDownloadedBytes + downloadedBytes;
// call progress
DownloadFile.downloadProgressListener.progress(totalDownloadedBytes, fileSize);
}
}
} catch (IOException e) {
e.printStackTrace();
Looper.prepare();
// Error
DownloadFile.downloadProgressListener.error(e.getMessage());
}
}
}).start();
}
}
DownloadProgressListener.java
import java.io.File;
public interface DownloadProgressListener {
void progress(int downloaded, int totalFileSize);
void success(File downloadedFile);
void error(String errorMessage);
}
Projects with Source Code + Video Tutorials
You can download our Java and Android Studio Projects with Source Code and Video Tutorials.
Sound Recorder App in Android Studio
How to create Modern Login and Register screen in Android Studio | Material UI Design | Part - 06
How to create custom Update Dialog with Example in Android Studio
If you have any Questions or Queries
You can mail us at info.learnoset@gmail.com
Follow us to learn Coding and get in touch with new Technologies.