我正在应用程序中下载图像以将其填充到用户界面上。
这是我用来下载该图像并将其保存到设备外部存储器的代码。
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 时是否可以检查图像是否正确加载。
我对此也做了很多研究,最后我通过检查图像长度克服了这个问题
URL url = new URL(url);
URLConnection conection = url.openConnection();
conection.connect();
fileLength = conection.getContentLength();
check fileLength
和下载的图像文件长度。如果相等或接近相等则下载成功。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)