• Home
  • DSA
  • iOS
  • Flutter
  • Android
    • Jetpack
    • Android Tutorials
    • Android development
    • Android Kotlin
  • 5G
  • 4G LTE
    • IoT
  • E-learning
  • Blog
  • Streaming
Friday, June 20, 2025
  • Home
  • DSA
  • iOS
  • Flutter
  • Android
    • Jetpack
    • Android Tutorials
    • Android development
    • Android Kotlin
  • 5G
  • 4G LTE
    • IoT
  • E-learning
  • Blog
  • Streaming
subscribe
subscribe to my newsletter!

"Get all latest content delivered straight to your inbox."

[mc4wp_form id="36"]
Codeplayon
Codeplayon
  • Home
  • DSA
  • iOS
  • Flutter
  • Android
    • Jetpack
    • Android Tutorials
    • Android development
    • Android Kotlin
  • 5G
  • 4G LTE
    • IoT
  • E-learning
  • Blog
  • Streaming
HomeAndroid tutorialAndroid download video from URL and save to internal storage
Oct. 10, 2019 at 6:26 am
Android tutorial

Android download video from URL and save to internal storage

6 years agoMay 22, 2022
download videoder
Android download video from URL and save to internal storage
5.5kviews

Android download video from URL and save to internal storage.  Hi Everyone in this Android Tutorial, I am sharing How to download a video in Android from a URL and save it to internal storage. here I am using a string video URL and downloading the video for these URLs. I am using AsyncTask for downloading videos and saving in the phone memory. Creating a folder for saving videos to internal storage

Android download video from URL and save to internal storage

Table of Contents

Toggle
  • Android download video from URL and save to internal storage
  • How to Create A Video streaming app in android studio

In android, if you want to learn to download a video from the URL you can just follow these simple steps.

Step 1: Create an android project with an empty Activity.

Start your android studio and create a project in with select an empty activity. and used a button in your XML file and findviewbyid in your main java file, Android download video from URL and save to internal storage.

Step 2: Open You Main.java File and add this code.

public class MainActivity extends AppCompatActivity {
private Button  downloadButton;
String fileN = null ;
public static final int MY_PERMISSIONS_REQUEST_WRITE_STORAGE = 123;
boolean result;
String urlString;Dialog downloadDialog; 

@SuppressLint({"SetJavaScriptEnabled", "JavascriptInterface"})
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(Constant.theme);
    setContentView(R.layout.activity_main); result = checkPermission();
if(result){
    checkFolder();
}
if (!isConnectingToInternet(this)) {
    Toast.makeText(this, "Please Connect to Internet", Toast.LENGTH_LONG).show();
} 

downloadButton = (Button)DialogView.findViewById(R.id.downloadButton);
 downloadButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(MainActivity.this, "Downloading", Toast.LENGTH_SHORT).show();
        newDownload(urlString);
        main_dialog.dismiss();
    }
}); 
 } 

 public static boolean isConnectingToInternet(Context context) {
    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null &&
            activeNetwork.isConnectedOrConnecting();
}  
 

// DownloadTask for downloding video from URL
 public class DownloadTask extends AsyncTask<String, Integer, String> {
        private Context context;
        private PowerManager.WakeLock mWakeLock;
        public DownloadTask(Context context) {
            this.context = context;
        }
        private NumberProgressBar bnp;
        @Override
        protected String doInBackground(String... sUrl) {
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
                java.net.URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP " + connection.getResponseCode()
                            + " " + connection.getResponseMessage();
                }

                int fileLength = connection.getContentLength();

                input = connection.getInputStream();
                fileN = "FbDownloader_" + UUID.randomUUID().toString().substring(0, 10) + ".mp4";
                    File filename = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
                            Constants.FOLDER_NAME, fileN);
                    output = new FileOutputStream(filename);

                byte data[] = new byte[4096];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    if (isCancelled()) {
                        input.close();
                        return null;
                    }
                    total += count;
                    if (fileLength > 0)
                        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 onPreExecute() {
            super.onPreExecute();
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                    getClass().getName());
            mWakeLock.acquire();
            LayoutInflater dialogLayout = LayoutInflater.from(MainActivity.this);
            View DialogView = dialogLayout.inflate(R.layout.progress_dialog, null);
            downloadDialog = new Dialog(MainActivity.this, R.style.CustomAlertDialog);
            downloadDialog.setContentView(DialogView);
            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(downloadDialog.getWindow().getAttributes());
            lp.width = (getResources().getDisplayMetrics().widthPixels);
            lp.height = (int)(getResources().getDisplayMetrics().heightPixels*0.65);
            downloadDialog.getWindow().setAttributes(lp);

            final Button cancel = (Button) DialogView.findViewById(R.id.cancel_btn);
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //stopping the Asynctask
                    cancel(true);
                    downloadDialog.dismiss();

                }
            });. 

            downloadDialog.setCancelable(false);
            downloadDialog.setCanceledOnTouchOutside(false);
            bnp = (NumberProgressBar)DialogView.findViewById(R.id.number_progress_bar);
            bnp.setProgress(0);
            bnp.setMax(100);
            downloadDialog.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            bnp.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            mWakeLock.release();
            downloadDialog.dismiss();
            if (result != null)
                Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
            else
                Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
            MediaScannerConnection.scanFile(MainActivity.this,
                    new String[]{Environment.getExternalStorageDirectory().getAbsolutePath() +
                            Constants.FOLDER_NAME + fileN}, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String newpath, Uri newuri) {
                            Log.i("ExternalStorage", "Scanned " + newpath + ":");
                            Log.i("ExternalStorage", "-> uri=" + newuri);
                        }
                    });

        }
    }

//hare you can start downloding video
 public void newDownload(String url) {
    final DownloadTask downloadTask = new DownloadTask(MainActivity.this);
    downloadTask.execute(url);
}

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public boolean checkPermission() {
    int currentAPIVersion = Build.VERSION.SDK_INT;
    if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MainActivity.this);
                alertBuilder.setCancelable(true);
                alertBuilder.setTitle("Permission necessary");
                alertBuilder.setMessage("Write Storage permission is necessary to Download Images and Videos!!!");
                alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
                    }
                });
                AlertDialog alert = alertBuilder.create();
                alert.show();
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
            }
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }
}


public void checkAgain() {
    if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MainActivity.this);
        alertBuilder.setCancelable(true);
        alertBuilder.setTitle("Permission necessary");
        alertBuilder.setMessage("Write Storage permission is necessary to Download Images and Videos!!!");
        alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            public void onClick(DialogInterface dialog, int which) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
            }
        });
        AlertDialog alert = alertBuilder.create();
        alert.show();
    } else {
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
    }
}


//Here you can check App Permission 
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_WRITE_STORAGE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                checkFolder();
            } else {
                //code for deny
                checkAgain();
            }
            break;
    }
}

//hare you can check folfer whare you want to store download Video
public void checkFolder() {
    String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/FBDownloader/";
    File dir = new File(path);
    boolean isDirectoryCreated = dir.exists();
    if (!isDirectoryCreated) {
        isDirectoryCreated = dir.mkdir();
    }
    if (isDirectoryCreated) {
        // do something\
        Log.d("Folder", "Already Created");
    }
}

How to Create A Video streaming app in android studio

 

 

Read More Tutorial 

  • Codeplayon Jetpack Compose Tutorial 
  • Codeplayon Android Tutorial 
  • Codeplayon Flutter Tutorial 
  • Codeplayon on Github
Tags :Androidandroid download file from url and save to internal storage exampleandroid download video from url and save to internal storageandroid tutorialdownload video file from url androiddownload video from facebookdownload video from twitterdownload video tiktokhow to download file from url in android programmatically
share on Facebookshare on Twitter
Shivam MalikOctober 10, 2019

Shivam Malik

Welcome to my blog! I’m Ritu Malik, and here at Codeplayon.com, we are dedicated to delivering timely and well-researched content. Our passion for knowledge shines through in the diverse range of topics we cover. Over the years, we have explored various niches such as business, finance, technology, marketing, lifestyle, website reviews and many others.
view all posts
How to create a video streaming from server in android
Android how to change application theme color programmatically

You Might Also Like

. Full Stop Punctuation
E-learning

” . ” Full Stop Punctuation – Usage and Significance 2023

Shivam Malik
What is Implicit and an Explicit Intent in Android?
Android development

What is the Difference Between an Implicit and an Explicit Intent in Android?

Shivam Malik
Android minecraft compass drawing App Example
Android tutorial

Android minecraft compass drawing App Example

Shivam Malik
Paytm Payment Gateway
Android tutorial

How to Integrate Paytm Payment Gateway in Android App 2024

Shivam Malik
Dynamic Launcher Icon and Name for Android App
Android tutorialAndroid development

Dynamic Launcher Icon and Name for Android App 2024

Shivam Malik
android user permission
Android tutorial

android user permission – How to check Grants Permissions at Run-Time?

Shivam Malik

Get Even More

"Get all latest content delivered straight to your inbox."
[mc4wp_form id="36"]

latest posts

Blog

The Essential Elements of a Secure Web Gateway and Its Role in Modern Business Networks

Shivam Malik
694
Blog

The Art of Crafting SEO Strategies That Stand the Test of Time

Shivam Malik
522
How-SAFe-Product-Owner-&-ITIL-Foundation-Training-Enhance-Agile-Service-Management
Blog

How SAFe® Product Owner and ITIL Foundation Training Enhance Agile Service Management

Shivam Malik
832
Blog

Enhancing Employee Satisfaction Through Efficient Payroll Systems

Shivam Malik
529

find me on socials

Search

Contact Info

Contact information that feels like a warm, friendly smile.

Email:Info.codeplayon@gmail.com
Website:Codeplayon

popular posts

Joinpd.com

How to Join a Pear Deck Session with JoinPD.com Code? 2023 Guide

7 months agoJanuary 8, 2025
rice purity test

What is Rice Purity Test Score Meaning: Check Score [2025]

6 months agoJanuary 3, 2025
Disneyplus.com/begin

How to Activate Disneyplus.com begin account 2025

6 months agoJanuary 5, 2025
Sitemap.Html
  • The Essential Elements of a Secure Web Gateway and Its Role in Modern Business Networks
  • The Art of Crafting SEO Strategies That Stand the Test of Time
  • How SAFe® Product Owner and ITIL Foundation Training Enhance Agile Service Management
  • Enhancing Employee Satisfaction Through Efficient Payroll Systems
  • Oklahoma City Mesothelioma Lawyer Vimeo
Codeplayon
  • Privacy Policy

Copyright © 2024 Codeplayon | NewsMozi Sitemap