您的位置:首页 > 其它

带缓存功能的图片查看器

2016-09-07 16:08 176 查看
public void loadImg() {
final String path = "http://8080:www.baidu.com/helle.jpg";
final File file = new File(getCacheDir(), getFileName(path));
//首先判断文件缓存是否存在
if (file.exists()) {
//通过文件的绝对路径构造Bitmap对象
Bitmap bp = BitmapFactory.decodeFile(file.getAbsolutePath());
ImageView iv = new ImageView(this);
iv.setImageBitmap(bp);
} else {
Thread thread = new Thread() {

@Override
public void run() {
try {
//1、获取URL对象
URL url = new URL(path);
//2、获取连接对象
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
//3、设置连接方法
conn.setRequestMethod("GET");
//读取超时
conn.setReadTimeout(5000);
//连接超时
conn.setConnectTimeout(5000);
//4、和服务器建立连接
conn.connect();
if (conn.getResponseCode() == 200) {
//5、拿到服务器返回的流
InputStream in = conn.getInputStream();
//6、开启文件输出流,把读取到的流写到本地
FileOutputStream fos = new FileOutputStream(file);
int len = 0;
byte[] b = new byte[1024];
while ((len = in.read(b)) != -1) {
fos.write(b, 0, len);
}
fos.close();

Bitmap bp = BitmapFactory.decodeFile(file
.getAbsolutePath());

// Bitmap bp = BitmapFactory.decodeStream(in);
// ImageView iv=new ImageView(getContext());
// iv.setImageBitmap(bp);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
thread.start();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  图片
相关文章推荐