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();
ProgressDialog使用,让进度条显示出Mb大小
于 2017-06-30 15:40:46 首次发布