2012-08-29 81 views
2

時顯示progressdialog我想顯示進度下載一個位圖:下載位圖

public static Bitmap getBitmapFromURL(String src) { 
    try { 
     URL url = new URL(src); 
     HttpURLConnection connection = (HttpURLConnection) url 
       .openConnection(); 
     connection.setDoInput(true); 
     connection.connect(); 

     InputStream input = connection.getInputStream(); 

     int fileLength = connection.getContentLength(); 

     // download the file 

     byte data[] = new byte[1024]; 
     long total = 0; 
     int count; 
     while ((count = input.read(data)) != -1) { 
      total += count; 
      // publishing the progress.... 
      progressDialog.setProgress((int) (total * 100/fileLength)); 
      Log.i("progre+ss", (int) (total * 100/fileLength) + " "); 
     } 

     Bitmap myBitmap = BitmapFactory.decodeStream(input); 
     return myBitmap; 
    } catch (IOException e) { 
     e.printStackTrace(); 
     return null; 
    } 
} 

它初始化用:

private void openprogresdialog() { 
    // TODO Auto-generated method stub 
    progressDialog = new ProgressDialog(PrMapGen.this); 
    progressDialog.setMessage("Generating File..."); 
    progressDialog.setCancelable(false); 
    progressDialog.setIndeterminate(false); 
    progressDialog.setMax(100); 
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
    progressDialog.show(); 

    new Thread() { 
     public void run() { 
      try { 
       generatePrMap(DataArray, 
         getIntent().getExtras().getString("project")); 

      } catch (Exception e) { 
      } 
      progressDialog.dismiss(); 
      projdata.close(); 
      finish(); 
     } 
    }.start(); 
} 

我的問題是這樣的:

當我使用while循環來更新進度條,沒有圖像被返回,當我刪除while循環時,位圖返回成功。

爲什麼?

在此先感謝

回答

2

這裏是一個小費,簡單的方法。

聲明AsyncTask

把你的代碼下載在doInBackgroud()圖像並設定進度內onUpdateProgress()。您也可以檢查this question