我正在使用 Volley 来缓存应用中的图片。内存缓存工作正常,但没有映像缓存在磁盘上。代码如下:
VolleySingleton.java
public class VolleySingleton {
public static final String TAG = "VolleySingleton";
private static VolleySingleton mInstance = null;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private VolleySingleton(Context context){
mRequestQueue = Volley.newRequestQueue(context);
mImageLoader = new ImageLoader(this.mRequestQueue,new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> mCache = new LruCache<String, Bitmap>(3);
@Override
public Bitmap getBitmap(String url) {
return mCache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
mCache.put(url,bitmap);
}
});
}
public static VolleySingleton getmInstance(Context context){
if(mInstance == null){
mInstance = new VolleySingleton(context);
}
return mInstance;
}
public RequestQueue getmRequestQueue(){
return this.mRequestQueue;
}
public ImageLoader getmImageLoader(){
return mImageLoader;
}
}
图像加载到CustomAdapter中 ChannelAdapter.java
private class ChannelAdapter extends BaseAdapter{
private LayoutInflater inflater;
private VolleySingleton volleySingleton;
public ChannelAdapter(Context context) {
super(context);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
volleySingleton = VolleySingleton.getmInstance(context);
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view == null){
view = inflater.inflate(R.layout.item,viewGroup,false);
}
NetworkImageView imageView = (NetworkImageView) view.findViewById(R.id.imageView);
TextView textView = (TextView) view.findViewById(R.id.textView);
textView.setText(tvChannel.getName());
imageView.setImageUrl(tvChannel.getImages().get(link,volleySingleton.getmImageLoader());
return view;
}
}
答案 0 :(得分:4)
好的,我解决了这个问题。这是因为我从服务器获得的图像在其响应中将缓存控制标记设置为 no-cache
Cache-Control: no-cache,no-cache,max-age=15552000
我通过修改库中的HttpHeaderParser.java
使凌空忽略了这个标签。现在它工作正常
答案 1 :(得分:1)
@ SathMk
我建议你不要忽略任何标签Cache-Control Header,如果你真的希望在标题说no-cahce时更长时间地缓存图像,那么你可以欺骗增加max-age如果它是非零的,就像在你的缓存。另外,你不会让缓存正常工作以进行数据请求。
if (headerValue != null) {
hasCacheControl = true;
String[] tokens = headerValue.split(",");
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i].trim();
if (token.equals("no-cache") || token.equals("no-store")) {
//Check if no-cache is there then still check again the max-age
if (token.startsWith("max-age=")) {
try {
maxAge = Long.parseLong(token.substring(8));
} catch (Exception e) {
return null;
}
}
} else if (token.startsWith("max-age=")) {
try {
maxAge = Long.parseLong(token.substring(8));
} catch (Exception e) {
}
} else if (token.equals("must-revalidate") || token.equals("proxy-revalidate")) {
maxAge = 0;
}
}
}
检查是否存在无缓存,然后再次检查max-age