我試圖在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