【问题标题】:Android - Displaying a progress bar while downloading a fileAndroid - 下载文件时显示进度条
【发布时间】:2010-11-09 02:55:27
【问题描述】:

我需要一些帮助。我一直在寻找几天试图找到解决我的问题的方法。我想在 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 线程

标签: android multithreading progress-bar


【解决方案1】:

使用异步任务。网上有几十个教程可以准确地说明您正在尝试做的事情。

【讨论】:

  • 是的,我查看了 AsyncTask,但是如何根据我的代码显示进度对话框并更新它?
  • Zarah 的回答为您指明了正确的方向。有大量关于如何在异步任务中启动、更新和关闭进度对话框的文档。
【解决方案2】:

你试过阅读documentation for AsyncTask吗?那里的示例正是您正在尝试做的事情。该示例使用方法publishProgress()onProgressUpdate()

OnPreExecute()上设置进度条,定期调用publishProgress(),在onProgressUpdate()上更新进度条。

【讨论】:

    猜你喜欢
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-26
    • 2011-03-02
    相关资源
    最近更新 更多