【问题标题】:How to handle incomplete image download in android?如何在android中处理不完整的图像下载?
【发布时间】:2012-10-01 10:21:48
【问题描述】:

我正在我的应用程序中下载图像以将其填充到 UI 中。

这是我用来将该图像下载并保存到设备外部存储器的代码。

        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,图像也没有正确下载。在这种情况下,图像看起来像这样

谁能告诉我如何正确处理这种情况?如果应用程序在写入数据时意外终止,那么如何处理这种情况?在这种情况下,图像被部分写入磁盘并且我的图像没有正确加载到图像视图中。

另外,请告诉我是否可以在将图像填充到 ImageView 时检查图像是否正确加载。

【问题讨论】:

  • 对图片使用占位符并显示它,直到图片下载完成。
  • @blackbelt.. 我正在后台下载这些图像。如何以编程方式确定图像下载是否不完整?
  • 您可以将内容长度(如果服务器在标头中有)与图像的大小进行比较。
  • @blackbelt.. 有超过 240 张图片。要检查内容长度,然后每次我需要向服务器请求并获取内容。然后就像每次启动应用程序时下载这 240 张图像一样。有没有其他办法?
  • 你应该只在第一次下载时检查

标签: android image download android-imageview


【解决方案1】:

我对此也做了很多研究,最后我通过检查图像长度来克服这个问题

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

检查fileLength 和下载的图像文件长度。如果相等或接近相等,则下载成功。

【讨论】:

  • 能否提供代码来比较 conection.getContentLength() 和下载的图片文件长度?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-19
  • 2011-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多