private ImageView mImageView;
private String murl;
private LruCache<String, Bitmap>cache;
public Pic_loader(){
int maxSize=(int) (Runtime.getRuntime().maxMemory())/4;
cache=new LruCache<String, Bitmap>(maxSize){
@Override
protected int sizeOf(String key, Bitmap value) {
// TODO Auto-generated method stub
return value.getByteCount();
}
};
}
public void addBitMapToCache(String url,Bitmap bitmap){
if(getBitMapFromCache(url)==null){
cache.put(url, bitmap);
}
}
public Bitmap getBitMapFromCache(String url){
return cache.get(url);
}
private Bitmap getBitMap(String url){
Bitmap bitmap=null;
try {
InputStream is=new URL(url).openConnection().getInputStream();
BufferedInputStream bif=new BufferedInputStream(is);
bitmap=BitmapFactory.decodeStream(bif);
is.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
public void GetPicByAsyncTask(ImageView imageView,final String url){
mImageView=imageView;
murl=url;
Bitmap bitmap=getBitMapFromCache(url);
if(bitmap==null){
new NewsAsynctask().execute(url);
}else{
if(imageView.getTag().equals(url)){//如果url不一致加不加载,放置在异步加载时的加载错误。
imageView.setImageBitmap(bitmap);
}
}
}
private class NewsAsynctask extends AsyncTask<String,Void, Bitmap>{
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
Bitmap bitmap=getBitMap(params[0]);
if(bitmap!=null){
addBitMapToCache(params[0], bitmap);
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(mImageView.getTag().equals(murl)){//如果url不一致加不加载,放置在异步加载时的加载错误。
mImageView.setImageBitmap(result);
}
}
}
}