ProgressDialog使用,让进度条显示出Mb大小

 ProgressDialog  pBar = new ProgressDialog(MainActivity.this);//进度条,在下载的时候实时更新进度,提高用户友好度
     pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
     pBar.setTitle("正在下载");
     pBar.setMessage("请稍候...");
     pBar.setProgress(0);
     pBar.setProgressNumberFormat("%1d Mb /%2d Mb");//这里设置的是进度条下面显示的文件大小和下载了多少
    // %1d Mb是下载的大小,
    // %2d Mb是文件的总大小 
     pBar.setCancelable(false);
//点击返回不取消 
     pBar.show(); 
     new Thread() {
        public void run() {
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(url);
            HttpResponse response;
            try {
                response = client.execute(get);
                HttpEntity entity = response.getEntity();
                int length = (int) entity.getContentLength();
                //获取文件大小 
                pBar.setMax((length/1024)/1024);
                //设置进度条的总长度,这里设置成Mb,默认的是Bit大小,转换成Mb 
                InputStream is = entity.getContent();
                FileOutputStream fileOutputStream = null;
                if (is != null) {
                    File file = new File( Environment.getExternalStorageDirectory(), "android.apk");
                    fileOutputStream = new FileOutputStream(file);
                    //这个是缓冲区,即一次读取10个比特,我弄的小了点,因为在本地,所以数值太大一下就下载完了, 
                    //看不出progressbar的效果。 
                    byte[] buf = new byte[1024];
                    //这是每次读取的大小 
                    int ch = -1;
                    int process = 0;
                    while ((ch = is.read(buf)) != -1) {
                        fileOutputStream.write(buf, 0, ch);
                        process += ch;
                        pBar.setProgress(process/(1024*1024));//这里就是关键的实时更新进度了!这里让显示的是Mb 
                    }
                }
                fileOutputStream.flush();
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.start();
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值