android从本地缓存和网络加载图片
一、实现的思路
1、获取网络地址path
2、建立url对象
3、建立url连接conn
4、设置conn的连接方法
5、获取conn的输入流
7、new一个byte[] 数组
8、建立一个本地的文件File,并获取file的outputstream
9、用outputstream将byte[]写入到文件中
10、bitmapfactory.decodefile(),获取bitmap对象,并显示到图片控件上。
二、代码
public void loadImg(){
String path="http://192.168.2.101:8080/ppa_web/image/wsn.jpg";
File file =new File(getCacheDir(), getFileName(path));
if (file.exists()) {
System.out.println("从本地缓存加载图片");
Bitmap bp=BitmapFactory.decodeFile(file.getAbsolutePath());
Message msg=new Message();
msg.obj=bp;
Handler.sendMessage(msg);
}else {
System.out.println("从网络加载图片");
try {
URL url = new URL(path);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
conn.connect();
if (conn.getResponseCode()==200) {
InputStream is=conn.getInputStream();
FileOutputStream fos=new FileOutputStream(file);
byte[] b=new byte[1024];
int len;
while ((len=is.read(b))!=-1) {
fos.write(b, 0, len);
}
Bitmap bp=BitmapFactory.decodeFile(file.getAbsolutePath());
Message msg=new Message();
msg.obj=bp;
Handler.sendMessage(msg);
}else {
Toast.makeText(this, "访问网络失败", 2000).show();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//根据网络地址获取文件名称
private String getFileName(String path) {
int index=path.lastIndexOf("/");
return path.substring(index);
}