java-更新进度对话框

我正在尝试制作一个可以帮助我评估从Web资源下载文件的时间的应用程序.我发现了2个样本:

Download a file with Android, and showing the progress in a ProgressDialog

http://www.helloandroid.com/tutorials/how-download-fileimage-url-your-device

第二个示例显示了较小的下载时间,但是我不明白如何使用它来更新进度对话框.我认为在第二种情况下应该使用“ while”表达来完成某些操作,但是我找不到.有人可以给我提些建议吗?

UPD:

第一个代码:

try {
            time1 = System.currentTimeMillis();
            URL url = new URL(path);
            URLConnection conexion = url.openConnection();
            conexion.connect();
            // this will be useful so that you can show a tipical 0-100% progress bar
            int lenghtOfFile = conexion.getContentLength();
            // downlod the file
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream("/sdcard/analyzer/test.jpg");

            byte data[] = new byte[1024];

            long total = 0;

          time11 = System.currentTimeMillis();
           while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                publishProgress((int)(total*100/lenghtOfFile));
                output.write(data, 0, count);
            }
            time22= System.currentTimeMillis()-time11;
            output.flush();
            output.close();
            input.close();


        } catch (Exception e) {}

        timetaken = System.currentTimeMillis() - time1;

第二个代码:

       long time1 = System.currentTimeMillis();
        DownloadFromUrl(path, "test.jpg");
        long timetaken = System.currentTimeMillis() - time1;

哪里

  public void DownloadFromUrl(String imageURL, String fileName) {  //this is the downloader method
 try {
         URL url = new URL(imageURL); //you can write here any link
         File file = new File(fileName);

        /*Open a connection to that URL. */
         URLConnection ucon = url.openConnection();

         /*
          * Define InputStreams to read from the URLConnection.
          */
         InputStream is = ucon.getInputStream();
         BufferedInputStream bis = new BufferedInputStream(is);

         /*
          * Read bytes to the Buffer until there is nothing more to read(-1).
          */
         ByteArrayBuffer baf = new ByteArrayBuffer(50);
         int current = 0;
         while ((current = bis.read()) != -1) {
                 baf.append((byte) current);
         }

         /* Convert the Bytes read to a String. */
         FileOutputStream fos = new FileOutputStream(PATH+file);
         fos.write(baf.toByteArray());
         fos.close();

 } catch (IOException e) {
         Log.d("ImageManager", "Error: " + e);
 }

因此,问题在于第一种方法的速度似乎要慢30%.

解决方法:

second example可能运行得更快,但它垄断了GUI线程. first approach使用AsyncTask更好;它允许GUI在下载进行时保持响应.

我发现将AsyncTaskSwingWorker进行比较很有帮助,如该example所示.

上一篇:使用alive-progress进度条可视化你的项目过程


下一篇:java.lang.IllegalStateException: Shutdown in progress