Android - 下载文件时显示进度条

时间:2010-11-09 02:55:27

标签: android multithreading progress-bar

我需要一些帮助。我一直在寻找寻找解决问题的方法。我想在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();

2 个答案:

答案 0 :(得分:2)

使用asynctask。网上有很多教程,正是为了你想要做的事情。

答案 1 :(得分:0)

您是否尝试过阅读documentation for AsyncTask?这个例子有完全你要做的事情。该示例使用方法publishProgress()onProgressUpdate()

OnPreExecute()设置进​​度条,定期致电publishProgress(),然后在onProgressUpdate()更新进度条。