[英]Android - Displaying a progress bar while downloading a file
我需要協助。 我一直在尋找試圖解決我的問題的方法的日子。 我想在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。 在線上有許多教程可以幫助您准確地進行嘗試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.