我需要帮助。我一直在寻找试图解决我的问题的方法的日子。我想在Android中下载文件时显示进度栏。我找到了足够的文件下载空间,但一直在努力弄清楚如何显示进度条。
这是我的下载代码:
String sURL = getString(R.string.DOWNLOAD_URL) + getString(R.string.DATABASE_FILE_NAME);
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(sURL);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
Header[] clHeaders = response.getHeaders("Content-Length");
Header header = clHeaders[0];
int totalSize = Integer.parseInt(header.getValue());
int downloadedSize = 0;
if (entity != null) {
InputStream stream = entity.getContent();
byte buf[] = new byte[1024 * 1024];
int numBytesRead;
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(file));
do {
numBytesRead = stream.read(buf);
if (numBytesRead > 0) {
fos.write(buf, 0, numBytesRead);
downloadedSize += numBytesRead;
//updateProgress(downloadedSize, totalSize);
}
} while (numBytesRead > 0);
fos.flush();
fos.close();
stream.close();
httpclient.getConnectionManager().shutdown();
最佳答案
使用asynctask。在线上有许多教程可以帮助您准确地进行尝试。