简体   繁体   中英

Display progress bar until download is complete - Android

I am using the following code for downloading the video from the internet:

class DownloadFile1 extends AsyncTask<String, Integer, String> {

    public String videoToDownload;
    public String fileName;

    @Override
    protected String doInBackground(String... params) {
        int count;

        try {
            mp4load(videoToDownload);
        } catch (Exception e) {
            // TODO: handle exception
        }

        return null;
    }

    public void mp4load(String urling) {
        try {
            System.out.println("Downloading");
            URL url = new URL(urling);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            //c.setDoOutput(true);
            con.connect();

            // String downloadsPath = Environment.getExternalStoragePublicDirectory();
            File SDCardRoot = Environment.getExternalStorageDirectory();

            File outputFile = new File(SDCardRoot, fileName);

            if (!outputFile.exists()) {
                outputFile.createNewFile();
            }

            FileOutputStream fos = new FileOutputStream(outputFile);

            int status = con.getResponseCode();

            InputStream is = con.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();
            System.out.println("Downloaded");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

I want to add progress bar until the video gets downloaded.The progress bar should be displayed from the start of the download to the end of the download in any format (ie) it can be a circular progress bar etc.How to do this?

I have a code to add progress bar in async task.Whether the following code is correct?

                        @Override
                        protected void onPostExecute(Void result) {
                            bar.dismiss();
                            super.onPostExecute(result);
                        }
                        @Override
                        protected void onPreExecute() {
                            bar = new ProgressDialog(activity);
                            bar.setMessage("Processing...");
                            bar.setIndeterminate(true);
                            super.onPreExecute();
                        }

Change your code like below :

class DownloadFile1 extends AsyncTask<String, Integer, String> {
    ProgressDialog bar;
    public String videoToDownload;
    public String fileName;
    private Context mContext;

    public DownloadFile1(Context context)
     {
      mContext=context;  
     }
    @Override
    protected void onPreExecute()
    {
       super.onPreExecute();
       bar = new ProgressDialog(mContext);
       bar.setMessage("Processing...");
       bar.setIndeterminate(true);
    }

    @Override
    protected String doInBackground(String... params) {
        int count;

        try {
            mp4load(videoToDownload);
        } catch (Exception e) {
            // TODO: handle exception
        }

        return null;
    }

    @Override
    protected String onPostExecute()
    {
      super.onPostExecute(result);
      bar.dismiss();
    }

    public void mp4load(String urling) {
        try {
            System.out.println("Downloading");
            URL url = new URL(urling);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            //c.setDoOutput(true);
            con.connect();

            // String downloadsPath = Environment.getExternalStoragePublicDirectory();
            File SDCardRoot = Environment.getExternalStorageDirectory();

            File outputFile = new File(SDCardRoot, fileName);

            if (!outputFile.exists()) {
                outputFile.createNewFile();
            }

            FileOutputStream fos = new FileOutputStream(outputFile);

            int status = con.getResponseCode();

            InputStream is = con.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();
            System.out.println("Downloaded");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

And change the calling like

DownloadFile1 downloadFile1 = new DownloadFile1(mContext); 

OR

DownloadFile1 downloadFile1 = new DownloadFile1(MainActivity.this); 

Then

downloadFile1.videoToDownload = video_url;
downloadFile1.fileName = video_url;
downloadFile1.execute();

make Progress dialog like below code.. make two method like below for show and hide.

    private ProgressDialog progressDialog; // it create local level of class.
        progressDialog=new ProgressDialog(MainActivity.this); // this line define into onCreateView method.
    private void showProgress(){
    progressDialog.setMessage("Loading");
    progressDialog.show();
}
private void closeProgress(){
    progressDialog.dismiss();
}

when start dowload before called showProgress() method end of download completed then show closeProgress().

 /**
     * Showing Dialog
     * */
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case progress_bar_type: // we set this to 0
            pDialog = new ProgressDialog(this);
            pDialog.setMessage("Downloading file. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setCancelable(true);
            pDialog.show();
            return pDialog;
        default:
            return null;
        }

Download Class

class DownloadFile1 extends AsyncTask<String, Integer, String> {

    public String videoToDownload;
    public String fileName;

    @Override 
    protected String doInBackground(String... params) {
        int count;

        try { 
            mp4load(videoToDownload);
        } catch (Exception e) {
            // TODO: handle exception 
        } 

        return null; 
    } 

    public void mp4load(String urling) {
        try { 
            System.out.println("Downloading");
            URL url = new URL(urling);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            //c.setDoOutput(true); 
            con.connect();

            // String downloadsPath = Environment.getExternalStoragePublicDirectory(); 
            File SDCardRoot = Environment.getExternalStorageDirectory();

            File outputFile = new File(SDCardRoot, fileName);

            if (!outputFile.exists()) {
                outputFile.createNewFile();
            } 

            FileOutputStream fos = new FileOutputStream(outputFile);

            int status = con.getResponseCode();

            InputStream is = con.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            } 
            fos.close();
            is.close();
            System.out.println("Downloaded");
        } catch (IOException e) {
            e.printStackTrace();
        } 
    }

Progress Update

/**
         * Updating progress bar
         * */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
       }



/**
         * After completing background task
         * Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            dismissDialog(progress_bar_type);


        }


}

Here is the best solution for your question,

AndroidNetworking.download(url,dirPath,fileName)
                 .setTag("downloadTest")
                 .setPriority(Priority.MEDIUM)
                 .build()
                 .setDownloadProgressListener(new DownloadProgressListener() {
                    @Override
                    public void onProgress(long bytesDownloaded, long totalBytes) {
                      // do anything with progress  
                    }
                 })
                 .startDownload(new DownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                      // do anything after completion
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error    
                    }
                });

you can find this FastNetworking library from below link,

https://github.com/amitshekhariitbhu/Fast-Android-Networking

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM