贴出来代码:
public class MainActivity extends Activity {
private ImageView ima;
private MemoryCache lruCache;
String path="http://android.apkbus.com/images/172034140lit.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lruCache=new MemoryCache();
ima= (ImageView) findViewById(R.id.imageView1);
// new ImageTask().execute();
Bitmap b= getBit(path);
ima.setImageBitmap(b);
}
class ImageTask extends AsyncTask<String, Void, Bitmap>{
@Override
protected Bitmap doInBackground(String... arg0) {
try {
URL url=new URL(path);
try {
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
InputStream in=conn.getInputStream();
Bitmap bit=BitmapFactory.decodeStream(in);
return bit;
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
ima.setImageBitmap(result);
lruCache.addBitmapToMemoryCache(path, result);
}
}
public Bitmap getBit(String path){
Bitmap bb= lruCache.getBitmapFromMemCache(path);
if(bb==null){
new ImageTask().execute();
}
return bb;
}
}
补充下。我的图片缓存类没有贴出。 不过是没有问题的。。。
先确认是否缓存中有图片
重点是看看缓存的图片是否正确生成,另外,调用 Bitmap bb= lruCache.getBitmapFromMemCache(path); 时的路径是否与缓存的图片对应。
最后,如果上述都正确,就需要看看函数 getBitmapFromMemCache 的实现是否有问题。
public Bitmap getBitmapFromCache(String url) {
Bitmap bitmap;
synchronized (mLruCache) { //mLruCache 强引用LruCache缓存
bitmap = mLruCache.get(url);
}
synchronized (mSoftCache) {
SoftReference bitmapSoft = mSoftCache.get(url);
if (bitmapSoft != null) {
bitmap = bitmapSoft.get();
mLruCache.put(url, bitmap);
mSoftCache.remove(url);
return bitmap;
}
}
return bitmap;
}
public void addBitmapToCache(String url, Bitmap bitmap) {
synchronized (mLruCache) {
System.out.println("addBitmapToCache()");
mLruCache.put(url, bitmap);
}
}