Android app要求在线更新时ProgressDialog显示MB形式,主要代码:
1.
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setTitle("App下载中...");
progressDialog.setProgressNumberFormat("%1d Mb /%2d Mb");
progressDialog.setCancelable(false);
progressDialog.show();
URL apk_url = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apk_url.openConnection();
connection.setConnectTimeout(5000);
InputStream inputStream = connection.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(inputStream);
byte[] bytes = new byte[1024];
int len = 0;
progressDialog.setMax(connection.getContentLength()/1024/1024);
int total = 0;
while ((len = bis.read(bytes)) != -1) {
fos.write(bytes, 0, len);
total += len;
//这里改变进度条
progressDialog.setProgress(total/1024/1024);
}
fos.close();
bis.close();
inputStream.close();
关键代码: progressDialog.setProgressNumberFormat("%1d Mb /%2d Mb");
progressDialog.setMax(connection.getContentLength()/1024/1024);
progressDialog.setProgress(total/1024/1024);
补充:这个可以配合String.format使用
%d前面的数字表示打印格子的位数
如果输出的内容位数超过了%d前面的数字会将内容全部输出,不足就补上空格