2011-04-23 22 views
1

喜所有 我怎樣才能使這個代碼等待,直到它完成下載圖像安卓doInBackground

有什麼我可以代替doInBackground(URL... paths)使其等待下載,然後繼續與其餘代碼

private class DownloadImageTask extends AsyncTask<URL, Integer, Bitmap> { 
    // This class definition states that DownloadImageTask will take String 
    // parameters, publish Integer progress updates, and return a Bitmap 
    protected Bitmap doInBackground(URL... paths) { 
     URL url; 
     try { 
      url = paths[0]; 
      HttpURLConnection connection = (HttpURLConnection) url 
        .openConnection(); 
      int length = connection.getContentLength(); 
      InputStream is = (InputStream) url.getContent(); 
      byte[] imageData = new byte[length]; 
      int buffersize = (int) Math.ceil(length/(double) 100); 
      int downloaded = 0; 
      int read; 
      while (downloaded < length) { 
       if (length < buffersize) { 
        read = is.read(imageData, downloaded, length); 
       } else if ((length - downloaded) <= buffersize) { 
        read = is.read(imageData, downloaded, length 
          - downloaded); 
       } else { 
        read = is.read(imageData, downloaded, buffersize); 
       } 
       downloaded += read; 
       publishProgress((downloaded * 100)/length); 
      } 
      Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0, 
        length); 
      if (bitmap != null) { 
       Log.i(TAG, "Bitmap created"); 
      } else { 
       Log.i(TAG, "Bitmap not created"); 
      } 
      is.close(); 
      return bitmap; 
     } catch (MalformedURLException e) { 
      Log.e(TAG, "Malformed exception: " + e.toString()); 
     } catch (IOException e) { 
      Log.e(TAG, "IOException: " + e.toString()); 
     } catch (Exception e) { 
      Log.e(TAG, "Exception: " + e.toString()); 
     } 
     return null; 

    } 

    protected void onPostExecute(Bitmap result) { 
     String name = ImageLink.substring(ImageLink 
       .lastIndexOf("/") + 1); 
     if (result != null) { 
      hasExternalStoragePublicPicture(name); 
      saveToSDCard(result, name); 
      isImage = true; 

     } else { 
      isImage = false; 

     } 
    } 
} 
+3

你的問題沒有意義。 'doInBackground()'*是*下載圖像。它不能等待自己完成。 – CommonsWare 2011-04-23 00:22:08

+0

@CommonsWare:我想剩下的代碼等待下載完成我不想讓代碼繼續下去,直到圖像完成,因爲即時下載超過1個圖像,並由於某些原因它們重疊,我結束了2圖像哪些是相同的??! – moe 2011-04-23 01:38:04

+0

顯示您創建DownloadImageTask實例的代碼。你正在創建多個實例嗎?如果是這樣,那可能是你的問題。 – Squonk 2011-04-23 01:52:15

回答

2

doInBackground())在後臺執行。 waits for the downloadcontinues with the rest of the code的部分是onPostExecute()。這是你可能要求的功能。

+0

這是正確的,AsyncTask使用說明當doInBackground完成時觸發onPostExecute()。這一切都在後臺,所以你將不得不通知你的UI線程任務已完成,並且它可以從內存或其他東西中加載圖像。 – 2011-04-23 02:23:52

+0

DSouza:我添加了onPostExecute(),但仍然是同樣的問題.... ???!我更新了原始問題上的代碼 – moe 2011-04-23 18:06:05

0

關於AsyncTask的一點是您的Activity(創建AsyncTask)中的主代碼不會等待。異步是異步的簡稱 - 意味着沒有預定時間框架的情況發生。

如果您希望在其他代碼可以執行之前完成下載或多次下載,那麼您需要以同步方式執行某些操作(不適用於Android活動),或者需要編寫代碼以在回調中等待。