如何在Android进度条中显示正在下载的文件剩余KB数。例如,剩余12kb / 120kb,然后是97kb / 120kb等等。
我们可以像图片中显示的那样拥有这个进度对话框。
我们可以像图片中显示的那样拥有这个进度对话框。
class DownloadFileAsync extends AsyncTask<String, String, String> {
private ProgressDialog mProgressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(UrlTestActivity.this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
@Override
protected String doInBackground(String... aurl) {
int count;
try {
for (int i = 0; i < 3; i++) {
URL url = new URL("http://nodeload.github.com/nexes/Android-File-Manager/zipball/master");
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream is = url.openStream();
File testDirectory = new File(Environment.getExternalStorageDirectory() + "/Folder");
if (!testDirectory.exists()) {
testDirectory.mkdir();
}
FileOutputStream fos = new FileOutputStream(testDirectory+ "/"+(i+100)+".zip");
byte data[] = new byte[1024];
long total = 0;
int progress = 0;
while ((count = is.read(data)) != -1) {
total += count;
int progress_temp = (int) total * 100 / lenghtOfFile;
publishProgress(""+ progress_temp);
if (progress_temp % 10 == 0 && progress != progress_temp) {
progress = progress_temp;
}
fos.write(data, 0, count);
}
is.close();
fos.close();
}
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
progressDialog.setMax(fileLength/1000);
publishProgress(String.valueOf(total /1000));
以下代码仅适用于API 11及以上版本
progressDialog. setProgressNumberFormat ("%1d kb of %2d kb");
您可以使用进度对话框,如文档中所讨论的那样。或者(也许更加优雅),您可以在活动的标题栏中使用进度指示器。在调用 setContentView
之前,在您的活动中添加以下行:
requestWindowFeature(Window.FEATURE_PROGRESS);
然后通过调用setProgress(int)
,您可以指示进度。当进度达到10000时,标题栏中的进度指示器会消失。请注意,如果您在非UI线程中确定进度,则应使用Handler调用setProgress
。
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
。 - Ted Hopp