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();
}
}
带缓存功能的图片查看器
最新推荐文章于 2021-06-24 13:32:08 发布