简体   繁体   中英

Progress bar while downloading file in android

In my Project I want to download the link the user enter. when user enter link to download I want to show progress bar to show the percentage of downloading. In this code I can show the progress bar but it doesn't show the progress of download.How I can show the percentage or progress of downloading. and how to finish it after download has finished successfully?

here is my code:

public class MyActivity extends Activity {
private long enqueue;
private DownloadManager dm;
final Context context = this;
public Button star_download, view_downlod;
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    star_download = (Button) findViewById(R.id.start_download);
    view_downlod = (Button) findViewById(R.id.view_download);


    star_download.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.alert_custom);
            dialog.setTitle("Downloading ...");

            // set the custom dialog components - text, image and button
            final EditText text = (EditText) dialog.findViewById(R.id.text);
            final String link = text.getText().toString();
            Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
            // if button is clicked, close the custom dialog
            dialogButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                        dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                        DownloadManager.Request request = new DownloadManager.Request(
                                Uri.parse(text.getText().toString()));
                        enqueue = dm.enqueue(request);

                        showDialog(progress_bar_type);

                }
            });
            dialog.show();
        }
    });

    view_downlod.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent();
            i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
            startActivity(i);
        }
    });


    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                long downloadId = intent.getLongExtra(
                        DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(enqueue);
                Cursor c = dm.query(query);
                if (c.moveToFirst()) {
                    int columnIndex = c
                            .getColumnIndex(DownloadManager.COLUMN_STATUS);
                    if (DownloadManager.STATUS_SUCCESSFUL == c
                            .getInt(columnIndex)) {

                        ImageView view = (ImageView) findViewById(R.id.imageView1);
                        String uriString = c
                                .getString(c
                                        .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                        view.setImageURI(Uri.parse(uriString));
                    }
                }
            }
        }
    };

    registerReceiver(receiver, new IntentFilter(
            DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case progress_bar_type:
            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;
    }
}
protected void onProgressUpdate(String... progress) {
    // setting progress percentage
    pDialog.setProgress(Integer.parseInt(progress[0]));
}

}

I am new with android,and I am really confused, Can anyone help me?

     class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread
         * Show Progress Bar Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Downloading file. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setCancelable(false);
            pDialog.show();
            getActivity().showDialog(progress_bar_type);
        }

        /**
         * Downloading file in background thread
         */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                Log.d("URl","Url====="+f_url[0]);
                URLConnection conection = url.openConnection();
                conection.connect();
                extn=f_url[0].split("XYZ/");
                Log.d("URlextn","Urlextn====="+extn[1]);

                // getting file length
                int lenghtOfFile = conection.getContentLength();

                // input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(), 8192);

//                File file = new File(Environment.DIRECTORY_DOCUMENTS /);

                // Output stream to write file
                //OutputStream output = new FileOutputStream(Environment.getExternalStoragePublicDirectory() +extn[1]);
                OutputStream output = null;
                File mydir = new File(Environment.getExternalStorageDirectory() + "/xyz/");
                if(!mydir.exists())
                    mydir.mkdirs();
                output = new FileOutputStream(mydir+"/"+extn[1]);
                Log.d("EXTERNAL PATH","EXTERNAL PATH===="+ Environment.getExternalStorageDirectory()+"/xyz/");
                byte data[] = new byte[4096];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        /**
         * 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);
            pDialog.dismiss();
            try{

                imagePath = Environment.getExternalStorageDirectory()+"/"+"xyz"+"/" + extn[1];

            }
            catch (ArrayIndexOutOfBoundsException | NullPointerException ne)
            {
                System.out.println("ArrayError:" + ne);
            }

            System.out.println("imagePath==" + imagePath);

            imgFile = new File(imagePath);

            galleryAddPic(imgFile, getActivity());


        }
    }

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