如何在android中显示字节数下载进度和数据下载百分比

时间:2014-11-18 10:25:46

标签: android

我从URL下载了一些数据。我想在进度对话框中显示一起下载的字节数和字节百分比。

现在我只能显示下载的字节数百分比。  这是我的代码

public class MainActivity extends ActionBarActivity {

    // button to show progress dialog
    Button btnShowProgress;

    // Progress Dialog
    private ProgressDialog pDialog;

    private ImageView my_image;

    // Progress dialog type (0 - for Horizontal progress bar)
    public static final int progress_bar_type = 0;

    // File url to download
    private static String file_url = "http://ibuildmartdev.agicent.com/data/projs/3/11_01.pdf?5";
    DownloadFileFromURL df;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setContentView(R.layout.activity_main);

        // show progress bar button
        btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
        // Image view to show image after downloading
        my_image = (ImageView) findViewById(R.id.my_image);

        /**
         * Show Progress bar click event
         * */
        btnShowProgress.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {
                // starting new Async Task
            df  =new DownloadFileFromURL();
            df.execute(file_url);
            }
        });
    }


    /**
     * Background Async Task to download file
     * */
    class DownloadFileFromURL extends AsyncTask<String, String, String> implements OnKeyListener {

        /**
         * Before starting background thread Show Progress Bar Dialog
         * */
        @SuppressWarnings("deprecation")
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Downloading file. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setMax(500);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setCancelable(true);
            pDialog.show();
            pDialog.setOnKeyListener(this);
        }

        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.connect();
                // getting file length
                int lenghtOfFile = conection.getContentLength();

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

                // Output stream to write file
                OutputStream output = new FileOutputStream(
                        "/sdcard/downloadedfile.jpg");

                byte data[] = new byte[2048];

                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
            pDialog.dismiss();

            // Displaying downloaded image into image view
            // Reading image path from sdcard
            /*String imagePath = Environment.getExternalStorageDirectory()
                    .toString() + "/downloadedfile.jpg";
            // setting downloaded into image view
            my_image.setImageDrawable(Drawable.createFromPath(imagePath));*/
        }

        @Override
        protected void onCancelled() {
            Log.i("main Activity", "Asyn task Cancled");
            super.onCancelled();
        }
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                df.cancel(false);
                pDialog.dismiss();
                Log.i("main Activity", "true");
                return true;
            }

            return false;![enter image description here][1]
        }

    }

此代码仅显示%的下载进度。但我想以%显示下载进度以及总下载字节数。

1 个答案:

答案 0 :(得分:1)

You can do this :

publishProgress("" + (int) ((total * 100) / lenghtOfFile)+ "lengthOfFile="+lengthOfFile); //You can use as a thing to split variable.Here, i used the name "lengthOfFile=" and i will get this through publish progress and split it there 


@Override
protected void onProgressUpdate(String... values) {
    // TODO Auto-generated method stub
    super.onProgressUpdate(values);
String str[]=values[0].split("lengthOfFile=");
String percent=str[0];
String bytes=str[1];

}