java监控BufferedInputStream下载进度
我正试图在Android上使用AsyncTask
下载一个文件。我想显示一个ProgressDialog
,它应该有一个进度条来显示下载的状态。我使用了onProgressUpdate()
函数,并在doInBackground()
函数中实现了对publishProgress()
的调用。但是,进度对话框仅在下载文件后弹出。我的代码:
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())
时,整个文件都被下载了。如何监控下载进度
# 1 楼答案
使用您自己的InputStream包装URL输入流,该InputStream只读取字节并“监视”状态,例如发送通知
很简单:
InputStream
是一个抽象类,只有一个抽象方法:public abstract int read() throws IOException;
在您的情况下,它应该从它包装的流中读取字节
这里的问题是如何显示进程栏:您必须知道总字节数。如果您的资源是静态的,您可以从HTTP头
content-length
获取它。否则,您需要适当的服务器支持或启发# 2 楼答案
此代码用于显示下载项目的总大小和下载大小
您可以使用AsyncTask在后台下载版本