简体   繁体   中英

Showing progress bar until the download completes - Android

I am using the following code to download a video from the website.The download function is working fine and I have a small problem with the progress bar. The progress bar remains the same and does not update itself with increasing values.

@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;
    }
}

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

    /**
     * Before starting background thread
     * Show Progress Bar Dialog
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(progress_bar_type);
    }

    @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();
        }
    }

    /**
     * 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);
    }
}

The progress bar remains exactly at 0% progress and disappears after the download is completed. How to change the updating part of the progress bar?

Inside your doInBackground call the publishProgress method passing an Integer to be set in the progress bar.

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

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

    return null;
}

You'll need to move the code form your method mp4load to the doInBackground in order to modify the code like this:

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();
            int fileLength = con.getContentLength();
            long total = 0;
            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
                total += len1;
                publishProgress((int) (total * 100 / fileLength));
            }
            fos.close();
            is.close();

The idea is simple, you need to get the size of the file and slowly update the progressbar with as you download the file.

Referring to the AsyncTask Docs , your progress type argument has to be integer, as your AsyncTask class is declared as follows.

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

Therefore, change the

public void onProgressUpdate(String..Progress)

to public void onProgressUpdate(Integer..Progress)

and then use the override annotation

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