我如何在android中绘制下载进度条

时间:2014-02-22 04:58:07

标签: android download

我要从我的服务器下载一个文件,我必须在%中绘制一个进度条,以显示剩余的时间和已下载的%。请告诉我怎么做。

1 个答案:

答案 0 :(得分:0)

我不确定哪些部件有问题...下载文件?得到进展的迹象?更新用户界面?

这里有一小段路程可以帮助您完成各个步骤:

以下代码将向您显示执行与服务器的连接以获取文件的输入流。我喜欢使用HttpRequest来执行此类操作。

String url = "www.thefilelocation.com";
HttpGet httpRequest = new HttpGet(url);
HttpParams parameters = new BasicHttpParams();
// set any params you like, like timeouts, etc.
HttpClient httpClient = new DefaultHttpClient(parameters);
HttpResponse response = httpClient.execute(httpRequest);

InputStream inputStream = response.getEntity().getContent();
Header contentLengthHeader = response.getFirstHeader("Content-Length");
long contentLength = Long.parseLong(contentLengthHeader.getValue());

String fileNameAndPath = "<some file name and path>";

saveFileWithProgressIndication(inputStream, contentLength, fileNameAndPath);

请记住,此代码是同步的,因此您可能希望使用单独的线程或异步任务在后台播放此代码。

此代码将为您提供输入流,但不会下载该文件。下一个代码将向您展示如何下载文件并监控进度。

private void saveFileWithProgressIndication(InputStream inputStream, long contentLength, String fileNameAndPath) throws IOException
{
File myFile = new File(filename);

FileOutputStream fout = null;

int totalSize = 0;
try
{
    fout = new FileOutputStream(filename);

    byte data[] = new byte[1024];
    int count;
    while ((count = inputStream.read(data, 0, 1024)) != -1)
    {
        fout.write(data, 0, count);
        totalSize += count;

        if (contentLength> 0)
               updateProgressInUi((double)totalSize / (double)contentLength);

    }

}
finally
{
    if (inputStream != null)
        inputStream.close();
    if (fout != null)
        fout.close();
}

}

此方法实际上将执行文件下载。下载的每1024个字节将触发对更新UI方法的调用(您可以根据需要修改它)。 最后一部分是更新UI:

private void updateProgressInUi(double percentage) // percentage will be between 0 and 1
{
  runOnUiThread(new Runnable() 
  {
     void run()
     {
        myLabel.setText( ((int)(percentage * 100)) + "%" );
     }
  });
}

您可以轻松更改此选项以更新进度条的值或您想到的任何其他内容。

希望这会有所帮助:)