设为首页 加入收藏

TOP

Android异步下载图片并且缓存图片到本地(二)
2014-11-23 23:57:03 来源: 作者: 【 】 浏览:21
Tags:Android 异步 下载 图片 并且 本地
quals("contact")) {
contact = new Contact();
contact.setId(Integer.valueOf(parser.getAttributeva lue(0)));
} else if (parser.getName().equals("name")) {
contact.setName(parser.nextText());
} else if (parser.getName().equals("image")) {
contact.setImage(parser.getAttributeva lue(0));
}
break;


case XmlPullParser.END_TAG:
if (parser.getName().equals("contact")) {
contacts.add(contact);
}
break;
}
}
return contacts;
}


/*
* 从网络上获取图片,如果图片在本地存在的话就直接拿,如果不存在再去服务器上下载图片
* 这里的path是图片的地址
*/
public Uri getImageURI(String path, File cache) throws Exception {
String name = MD5.getMD5(path) + path.substring(path.lastIndexOf("."));
File file = new File(cache, name);
// 如果图片存在本地缓存目录,则不去服务器下载
if (file.exists()) {
return Uri.fromFile(file);//Uri.fromFile(path)这个方法能得到文件的URI
} else {
// 从网络上获取图片
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
if (conn.getResponseCode() == 200) {


InputStream is = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
is.close();
fos.close();
// 返回一个URI对象
return Uri.fromFile(file);
}
}
return null;
}
}


Serivce类中,注意以下几点


1.HttpURLConnection conn = (HttpURLConnection) url.openConnection();获取一个链接,从而进行通讯2.怎么利用XxmlPullPaser类去解析XML,从而把数据封装成对象


3.getImageURI(String path, File cache) 这个方法具体实现


4.Uri.fromFile(file);这个方法能够直接返回一个Uri来


首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Java的IO操作中关闭流的注意点 下一篇在你的 Sliverlight 应用中集成动..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: