我试图在Android上使用AsyncTask
下载文件。我想显示一个ProgressDialog
,它应该有一个进度条来显示下载的状态。我正在使用onProgressUpdate()
函数,并在我的doInBackground()
函数中实现了对publishProgress()
的调用。但是,下载文件后,进度对话框只弹出。我的代码:监视BufferedInputStream下载进度
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())
整个文件下载。我如何监视下载进度?
谢谢!最后一件事:'ByteListener'应该是'StreamListener',而不是?如果你解决,我可以接受你的答案:) – Keelan 2013-05-13 09:47:51
你能改变这一点,亚历克斯? – Keelan 2013-05-15 07:17:47