这篇文章可能对您有用:
http://huuah.com/android-progress-bar-and-thread-updating/
在线程的 run() 方法中,您可以调用如下函数:
public boolean download(String url, String path, String fileName, Handler progressHandler) {
try {
URL sourceUrl = new URL(formatUrl(url));
if (fileName == null || fileName.length() <= 0) {
fileName = sourceUrl.getFile();
}
if (fileName == null || fileName.length() <= 0) {
throw new Exception("EMPTY_FILENAME_NOT_ALLOWED");
}
File targetPath = new File(path);
targetPath.mkdirs();
if (!targetPath.exists()) {
throw new Exception("MISSING_TARGET_PATH");
}
File file = new File(targetPath, fileName);
URLConnection ucon = sourceUrl.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(100);
int current = 0;
int totalSize = ucon.getContentLength();
while ((current = bis.read()) != -1) {
baf.append((byte) current);
// BEGIN - Handler feedback
if (progressHandler != null && (baf.length() % 100) == 0) {
Message msg = progressHandler.obtainMessage();
Bundle b = new Bundle();
if (totalSize > 0) {
b.putInt("total", totalSize);
b.putInt("step", baf.length());
b.putBoolean("working", true);
}
msg.setData(b);
progressHandler.handleMessage(msg);
}
// END
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
// BEGIN - Handler feedback
if (progressHandler != null) {
Message msg = progressHandler.obtainMessage();
Bundle b = new Bundle();
if (totalSize > 0) {
b.putInt("total", 0);
b.putInt("step", 0);
b.putBoolean("working", false);
}
msg.setData(b);
progressHandler.handleMessage(msg);
}
// END
return file.exists();
}
这样做,您可以更准确地反馈下载的实际进度(每个字节的字节数)。