LruCaChe缓存
把图片的加载利用LruCaChe进行缓存,无需每一次都请求网页图片,缓存可以有效的使APP节省流量。
1.创建LruCaChe缓存类
MyApplication/app/src/main/java/com/example/myapplication/ImageLoader.java
//创建Cache
private LruCache<String, Bitmap> mCaches;
public ImageLoader(){
//构造方法
//获取最大可用内存
int maxMemory = (int) Runtime.getRuntime().maxMemory();
//缓存为内存的四分之一
int cacheSize = maxMemory / 4;
mCaches = new LruCache<String, Bitmap>(cacheSize){
@Override
protected int sizeOf(String key, Bitmap value) {
//每次加入内存缓存的时候进行调用,把value的实际大小放进去
return value.getByteCount();
}
};
}
2.增加缓存和读取缓存的方法
MyApplication/app/src/main/java/com/example/myapplication/ImageLoader.java
/**
* 增加到缓存
* @param url
* @param bitmap
*/
public void addBitmapToCache(String url, Bitmap bitmap){
//判断缓存中是否有这个值
if(getBitmapFromCache(url) == null){
mCaches.put(url, bitmap);
}
}
/**
* 从缓存中读取数据
* @param url
* @return
*/
public Bitmap getBitmapFromCache(String url){
//获取缓存的对象
return mCaches.get(url);
}
3.调用的方法和AsyncTask下载图片
MyApplication/app/src/main/java/com/example/myapplication/ImageLoader.java
/**
* 根据url获取图片的Bitmap对象
* @param urlString
* @return
*/
public Bitmap getBitmapFromURL(String urlString){
Bitmap bitmap;
InputStream is = null;
try {
URL url = new URL(urlString);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
is = new BufferedInputStream(connection.getInputStream());
bitmap = BitmapFactory.decodeStream(is);
connection.disconnect();
return bitmap;
} catch (java.io.IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public void showImageByAsyncTask(ImageView imageView,String url){
//判断缓存中是否有
Bitmap bitmap = getBitmapFromCache(url);
if(bitmap == null){
//缓存中没有就去下载
new NewsAsyncTask(imageView, url).execute(url);
}else{
imageView.setImageBitmap(bitmap);
}
}
/**
* AsyncTask的方式把图片放入view
*/
private class NewsAsyncTask extends AsyncTask<String, Void, Bitmap>{
private ImageView mImageView;
private String murl;
public NewsAsyncTask(ImageView imageView, String url){
mImageView = imageView;
murl = url;
}
@Override
protected Bitmap doInBackground(String... strings) {
String url = strings[0];
//从网络中获取图片
Bitmap bitmap = getBitmapFromURL(url);
if(bitmap != null){
//增加到缓存
addBitmapToCache(url, bitmap);
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
//防止图片重复判断唯一性
if(mImageView.getTag().equals(murl)) {
mImageView.setImageBitmap(bitmap);
}
}
}
4.NewsAdapter调用方法
MyApplication/app/src/main/java/com/example/myapplication/NewsAdapter.java
private ImageLoader mImageLoader;
public NewsAdapter(Context context, List<NewBean> data){
//构造方法
mImageLoader = new ImageLoader();
}
//调用如下:
mImageLoader.showImageByAsyncTask(viewHolder.newPic, mList.get(position).getPicUrl());
评论