Updating progress dialog

前端 未结 2 1533
轻奢々
轻奢々 2021-01-21 04:19

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,

相关标签:
2条回答
  • 2021-01-21 05:01

    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.

    0 讨论(0)
  • 2021-01-21 05:11

    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.

    0 讨论(0)
提交回复
热议问题