我正在尝试使用 LRUcache 来缓存我的应用程序从 Web 下载的一些图像。我已经阅读了来自 android 开发人员的教程,但我无法在我的 LRUcache 中添加任何内容。这是我的代码,
class myloader extends Activity{ String url;ImageView imview;Bitmap map;LruCache<String, Bitmap> myCache=new LruCache<String, Bitmap> (5*1024*1024)
class load extends AsyncTask<String, Void, Bitmap>{
WeakReference <ImageView> ref=new WeakReference<ImageView>(imview);
String url2;
public load(ImageView imageView) {
ref = new WeakReference<ImageView>(imageView);
}
@Override
protected Bitmap doInBackground(String... params) {
try {
u=new URL(params[0]);
map=BitmapFactory.decodeStream(u.openConnection().getInputStream(),null,listDimensions());
myCache.put(url,map);
} catch (MalformedURLException e) {e.printStackTrace();
} catch (IOException e) {e.printStackTrace();}
return map;
}
@Override
protected void onPostExecute(Bitmap result) {
if (ref != null) {
ImageView imageView = ref.get();
toLoad bitmapDownloaderTask = getBitmapDownloaderTask(imageView);
if (this == bitmapDownloaderTask) {
imageView.setImageBitmap(result);
}
}
} public void download(String theurl,ImageView im) { url=theurl; // here i check for lrucache items
imview=im;
if (cancelPotentialDownload(url, imview)) {
toLoad task = new toLoad(imview);
DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task);
Bitmap finalBit=myCache.get(url);
if (finalBit!=null){
imview.setImageBitmap(finalBit);
}else{
imview.setImageDrawable(downloadedDrawable);
task.execute(url);
}
t=myCache.putCount();
}
}
然后从我的适配器类的 getview() 我调用 myloader,传递一个 imageview 和一个图像 url