2012-10-01 76 views
1

我在我的應用程序中下載圖像以將其填充到UI。如何在Android中處理不完整的圖像下載?

這裏是我正在使用的代碼下載&將該圖像保存到設備的外部存儲器。

 File firstDirectory=new File(Environment.getExternalStorageDirectory()+"/Catalog");  
     if (firstDirectory.exists()==false) 
     { 
      firstDirectory.mkdir(); 
     } 

     for (int i = 0; i <list.size() && !isCancelled(); i++) { 

      Content content= list.get(i); 
      try 
       { 

      File firstFile =new File(firstDirectory+"/"+content.getId()+".jpeg"); 
      if (firstFile.exists()==false || firstFile.length()==0) 
      {    
       Boolean status=firstFile.createNewFile(); 
       HttpClient httpClient = new DefaultHttpClient(); 
       HttpGet httpGet = new HttpGet(kSubURL+content.getPublisherID()+"&tid="+content.getId()+"_370&tp=i"); 
       HttpResponse resp = httpClient.execute(httpGet); 
       HttpEntity entity= resp.getEntity(); 
       InputStream is = entity.getContent(); 
        FileOutputStream foutS = new FileOutputStream(firstFile); 

        byte[] buffer = new byte[1024];     
        long total = 0; 
        int count; 
        while ((count = is.read(buffer)) != -1) { 
         total += count; 
         foutS.write(buffer, 0, count); 
        } 

        foutS.close(); 
        is.close(); 
      } 

     } catch (MalformedURLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

此代碼可正常工作,下載&保存圖像到設備上。但問題是,有時圖像沒有完全下載。如何處理這種情況?儘管響應代碼是200,但圖像沒有正確下載。在這種情況下,圖像看起來像這樣

enter image description here

誰能告訴我如何正確處理這種情況?如果應用程序在寫入數據時意外終止,那麼應如何處理該情況?在這種情況下,圖像部分寫入磁盤&我的圖像沒有正確加載到圖像視圖。

另外,請告訴我是否可以或不可以檢查圖像是否正確加載或不填充到ImageView上。

+0

使用圖像的佔位符並顯示它,直到圖像完成下載。 – Blackbelt

+1

@blackbelt ..我在後臺下載這些圖片。如何以編程方式查明圖像下載是否不完整? – Bharath

+0

您可以將圖像大小與內容長度(如果服務器在標題中包含該長度)進行比較。 – Blackbelt

回答

1

我還做了很多這樣的研究,最後我通過檢查圖像長度

URL url = new URL(url); 
URLConnection conection = url.openConnection(); 
conection.connect(); 
fileLength = conection.getContentLength(); 

檢查fileLength和下載的鏡像文件長度克服這一點。如果它相等或接近相等,則成功下載。

相關問題