我正在尝试使用AsyncTask
Android 下载文件。我想显示一个ProgressDialog
应该有一个进度条来显示下载状态的。我正在为此使用该函数并在我的函数onProgressUpdate()
中实现了对的调用。但是,只有在下载文件后才会弹出进度对话框。我的代码:publishProgress()
doInBackground()
protected Long doInBackground(URL...urls) {
for (int i = 0; i < urls.length; i++) {
url = urls[i];
try {
URLConnection conn = url.openConnection();
conn.connect();
totalSize = conn.getContentLength();
BufferedInputStream bis = new BufferedInputStream(url.openStream());
FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/forvo_temp.mp3");
BufferedOutputStream bos = new BufferedOutputStream(fos,1024);
byte [] data = new byte[1024];
int x=0; int c=0;
while((x=bis.read(data,0,1024))>=0){
bos.write(data,0,x);
c += 1024;
publishProgress(c);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return 0L; // Don't know what to do with this
}
protected void onProgressUpdate(Integer...args) {
pd = ProgressDialog.show(context, "Downloading...", "Downloading...", true, false);
pd.setProgress(args[0] / totalSize);
}
我猜我打电话时会下载整个文件new BufferedInputStream(url.openStream())
。如何监控下载进度?