Android的 - 显示一个进度条,而下载文件 [英] Android - Displaying a progress bar while downloading a file
本文介绍了Android的 - 显示一个进度条,而下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一些帮助。我一直在寻找了几天试图找到解决我的问题。我想显示一个进度条,同时下载在Android中的文件。我发现足够的下载文件,但一直在努力弄清楚如何显示进度条。
下面是我的下载code:
字符串SURL =的getString(R.string.DOWNLOAD_URL)+的getString(R.string.DATABASE_FILE_NAME);
HttpClient的HttpClient的=新DefaultHttpClient();
HTTPGET HTTPGET =新HTTPGET(SURL);
HTT presponse响应= httpclient.execute(HTTPGET);
HttpEntity实体= response.getEntity();
标题[] clHeaders = response.getHeaders(内容长度);
标题标题= clHeaders [0];
INT totalSize =的Integer.parseInt(header.getValue());
INT downloadedSize = 0;
如果(实体!= NULL){
InputStream的流= entity.getContent();
中byte buf [] =新的字节[1024 * 1024];
INT numBytesRead;
的BufferedOutputStream FOS =新的BufferedOutputStream(新的FileOutputStream(文件));
做 {
numBytesRead = stream.read(BUF);
如果(numBytesRead大于0){
fos.write(BUF,0,numBytesRead);
downloadedSize + = numBytesRead;
//的UpdateProgress(downloadedSize,totalSize);
}
}而(numBytesRead大于0);
fos.flush();
fos.close();
stream.close();
。httpclient.getConnectionManager()关闭();
解决方案
使用的AsyncTask的。有几十个教程在线为正是你想要做什么。
I need some help. I have been searching for days trying to find solution to my problem. I would like to show a progress bar while downloading a file in Android. I found enough to download the file but have struggled to figure out how to display a progress bar.
Here is my download code:
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();
解决方案
Use an asynctask. There are dozens of tutorials online for exactly what you're trying to do.
这篇关于Android的 - 显示一个进度条,而下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文