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

3

我需要一些帮助。我已经搜索了几天,试图找到解决我的问题的方法。我想在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();

你必须在单独的线程中进行下载。否则,你的代码将会阻塞主UI线程,从而导致整个屏幕挂起。 - xandy
2个回答

2

使用异步任务(AsyncTask)。网络上有许多针对您正在尝试完成的内容的教程。


是的,我已经看过AsyncTask了,但是根据我的代码,我该如何显示进度对话框并更新它呢? - Michael Little
Zarah的回答指引了你正确的方向。有很多关于如何在异步任务中启动、更新和取消进度对话框的文档。 - Falmarri

0
你尝试过阅读AsyncTask文档吗?那里的示例恰好是你想要做的。该示例使用了publishProgress()onProgressUpdate()方法。
OnPreExecute()中设置进度条,定期调用publishProgress(),并在onProgressUpdate()中更新进度条。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接