您的位置:首页 > 理论基础 > 计算机网络

android 加载网络数据(3)

2016-06-29 15:18 519 查看
加载网络数据

public class ImageCacheUtils {
private LruCache<String, Bitmap> lruCache;
private File dirFile;
public void init(){

long max = Runtime.getRuntime().maxMemory();
int maxSize =(int)max/6;
lruCache = new LruCache<String, Bitmap>(maxSize){
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes()*value.getHeight();
}
};
}
public Bitmap ImageLoad(final String path,final ImageView iv){

//先去缓存中去 查找----》本地----》网络
Bitmap b1=getBitMapFromLru(path);
if(b1!=null){
return b1;
}
//从本地取出
Bitmap b2=getBitMapFromDir(path);
if(b2!=null){
return b2;
}

Bitmap b3=getBitmapFromNet(path);
if(b3!=null){
return b3;
}
return null;
}
/**
* 缓存中查找
*/
public Bitmap getBitMapFromLru(String path){
return lruCache.get(path);
}
/**
* 从本地查找
* http:..../xx.jpg
*/
public Bitmap getBitMapFromDir(String path){
File file = Environment.getDownloadCacheDirectory();
File f = new File(file,path);
Bitmap bitmap = BitmapFactory.decodeFile(f.getPath());
if(bitmap!=null){
//在本地存在
lruCache.put(path, bitmap);
return bitmap;
}
return null;
}
/**
* 从网络中下载
*/
public Bitmap getBitmapFromNet(String path){
try {
URL url = new URL(path);
URLConnection connection =url.openConnection();
InputStream is = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
if(bitmap!=null){
//1.缓存   2.本地
lruCache.put(path, bitmap);
OutputStream os = new FileOutputStream(path);
int len=0;
byte[] by=new byte[1024];
while((len=is.read(by))!=-1){
os.write(by,0,len);
}
return bitmap;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

}


加载网络数据
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: