3

I am trying to make an application that can help me to evaluate the time to download the file from a web resource. I have found 2 samples:

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

and

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

The second example shows a smaller download time, but I cannot understand how to update progress dialog using it. I think something should be done with "while" expression in second case, but I cannot find what. Could someone give me any piece of advice?

UPD:

1st code:

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;

2nd code:

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

Where

  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);
 }

So the thing is that first method seems to be slower for about 30%.

Community
  • 1
  • 1
StalkerRus
  • 411
  • 1
  • 10
  • 20

2 Answers2

2

The second example may run faster, but it monopolizes the GUI thread. The first approach, using AsyncTask, is better; it allows the GUI to stay responsive as the download proceeds.

I found it helpful to compare AsyncTask with SwingWorker, as shown in this example.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • I execute the 2nd method in Asynctask. – StalkerRus Apr 02 '11 at 18:31
  • Well, the 1st code has a 1024 byte buffer, while the 2nd has only 50. – trashgod Apr 02 '11 at 18:38
  • I tried to reduce buffer to the 50. But I did not see any changes in performance. – StalkerRus Apr 02 '11 at 18:53
  • You said, "1st code I download a file approximately 30% slower" and "first method seems to be faster for about 30%." This seems like a contradiction. I note that `AsyncTask` has to interleave it's operation with the GUI to show progress, so 30% seems plausible. – trashgod Apr 02 '11 at 19:01
  • Sorry, I corrected the error. Is it possible to insert second code to Asynctask with updating the progress dialog? Or in this case I will have just the same performance decrease? Or may be I can improve performance of the first code? – StalkerRus Apr 02 '11 at 19:12
  • Other than buffer size, I'm not seeing much difference in the stream handling. Of course, the only way to know is to profile, much as you are doing already. Looking closer, you might try calling `publishProgress()` less frequently, perhaps every 10 or 100 bytes. – trashgod Apr 02 '11 at 19:20
  • I suspect that you'll have to determine how often to call `publishProgress()` empirically, based on the typical value of `count`. The same would be true of increasing the buffer size, as @Peter suggests. The optimum value may also depend on the connection type: 3G v. WiFi, etc. – trashgod Apr 02 '11 at 23:50
1

first link is best. But i can't provide code( it's home comp) in monday or later i can provide full function. But :

private class DownloadFile extends AsyncTask<String, Integer, String>{
    @Override
    protected String doInBackground(String... url) {
        int count;
        try {
            URL url = new URL(url[0]);
            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/somewhere/nameofthefile.ext");

            byte data[] = new byte[1024];

            long total = 0;

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

            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {}
        return null;
    }

this class are best for it ( imho) . publishProgress it's simple function where u have max two lines. Set max and set current. How u can see in this code lenghtOfFile it's how many bytes have ur file. total-current progress ( example 25 from 100 bytes) . Run this class easy : DownloadFile a = new DownloadFile(); a.execute(value,value);//or null if u not using value. Hope u understand me , im not good speaking on english.

Peter
  • 2,480
  • 6
  • 39
  • 60
  • I understand how it works, but I found out that using 1st code I download a file approximately 30% slower than using second code. I cannot understand why. – StalkerRus Apr 02 '11 at 18:21
  • byte data[] = new byte[1024]; u need set new value here for example 16000 . And it's incresa download speed – Peter Apr 02 '11 at 20:23