2011-12-11 62 views
0

我正在製作一個應用程序,下載大約231張圖片,其中150張顯示在列表視圖中,其餘圖片在圖片視圖中以全尺寸顯示在單獨的活動中。第一次運行應用程序時,圖像下載大約需要4分鐘或5分鐘(我需要一個進度條來顯示它們總共下載了多少圖片),然後在下載圖像後將它們保存到sd卡。然後,應用程序的連續啓動將從SD卡加載圖像,而不是重新下載它們。很多圖片的進度條

  1. 這是最好的方式去做這件事嗎?
  2. 如何製作進度條?我只成功地製作了適用於一個圖像的進度條

回答

1

我知道這樣做的最佳方式是使用asynctask。因爲它可以讓你執行一些後臺工作並同時更新UI(在你的情況下,進度條)。

這是我怎麼會去這樣做的例子代碼..

ProgressDialog mProgressDialog = new ProgressDialog(YourActivity.this); 
mProgressDialog.setMessage("A message"); 
mProgressDialog.setIndeterminate(false); 
mProgressDialog.setMax(100); 
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
DownloadFile downloadFile = new DownloadFile(); 
downloadFile.execute("the url to the file you want to download"); 

這是您的AsyncTask將如何看一個例子。

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

     // download 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; 
} 

上面的ALWAYS方法在後臺運行,你不應該從那裏更新任何用戶界面。 在另一方面,onProgressUpdate運行在UI線程上,所以你會改變進度條:如果你想一旦文件執行一些代碼

@Override 
public void onProgressUpdate(String... args){ 
    // here you will have to update the progressbar 
    // with something like 
    mProgressDialog.setProgress(args[0]); 
} 
} 

你也想重寫onPostExecute方法已完全下載。

+0

感謝您的迴應!我會研究這個! – Vokara1228

+0

這會說(1/231)然後(2/231)等等嗎? – Vokara1228

+0

是的,如果你也想要它。當我在進度對話框中設置消息時,你可以更新進度消息,比如下載1/10或者在圖片完成時,在asynctask的onPostExecute方法中。 –