图片缓存的主要三步骤:
一、从缓存中获取图片
二、如果缓存中未获取图片,则从存储卡中获取
三、如果存储卡中未获取图片,则从网络中获取
public class ImageCache{ private static final String TAG = "ImageCache";
private ExecutorService mThreadPool; //写个单例模式 private static ImagCache mInstance; public synchronized static ImageCache getInstance(){ if(mInstance == null) mInstance = new ImageCache; return mInstance; } private Image(){ int maxSize = (int)(Runtime.getRuntime().maxMemory()/8); mLruCache = new LruCache<String, Bitmap>(maxSize){ @Override protected int sizeOf(String key, Bitmap value) { if(value !=null){ return value.getRowBytes()*value.getHeight(); } return 0; } };
mThreadPool = Executors.newFixedThreadPool(5);
} //获取图片格式 private String getImagrType(String url){ String[] split = url.split("\."); return split[split.length-1]; } //从缓存中获取图片 private Bitmap getBitmapFromCache(String url){ android.util.Log.d(TAG, "load from cache....."); return mLruCache.get(url); } //从磁盘中获取图片 private Bitmap getBitmapFromDisk(String url){ android.util.Log.d(TAG, "load from disk...."); return BitmapFactory.decodeFile(getCacheDir()+url); } //将图片加入缓存 private void addToLru(final String url,Bitmap bitmap){ if( getBitmapFromCache(url) != null) return ; android.util.Log.d(TAG, "add to Lru..."); mLruCache.put(url, bitmap); } //将图片写入磁盘 private void addToDisk(String url,Bitmap bitmap,String type) throws IOException{ if(getBitmapFromDisk(url) != null) return; android.util.Log.d(TAG, "add to disk....."); FileOutputStream stream = new FileOutputStream(getCacheDir()+url); if(type.equalsIgnoreCase("png")){ bitmap.compress(CompressFormat.PNG, 100, stream); }else{ bitmap.compress(CompressFormat.JPEG, 100, stream); } stream.close(); addToLru(url, bitmap); } //获取磁盘缓存路径 private static String getCacheDir(){ String dir = null; if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ dir = Environment.getExternalStorageDirectory()+File.separator+"Matrial"+File.separator +"image"+File.separator; }else{ dir = App.context.getCacheDir()+File.separator+"image"+File.separator; } return mkdir(dir); } private static String mkdir(String dir){ File file =new File(dir); if(!file.exists()){ file.mkdirs(); } return dir; }
//网络下载图片
public void load(final String url, final OnImageLoadedListener l) {
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Constants.SUCCESS:
if(l != null) l.onImage((Bitmap) msg.obj);
break;
case Constants.FAILED:
if(l != null) l.onImage(null);
break;
}
}
};
final String key = Encrypt.md5(url);
Bitmap bmp = loadByLru(key);
if(bmp != null) {
handler.obtainMessage(Constants.SUCCESS, bmp).sendToTarget();
return;
}
bmp = loadByDisk(key);
if(bmp != null) {
handler.obtainMessage(Constants.SUCCESS, bmp).sendToTarget();
return;
}
mThreadPool.execute(new Runnable() {
@Override
public void run() {
DefaultHttpClient client = null;
try {
System.out.println("get by network.........................................");
client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
if(response.getStatusLine().getStatusCode() == 200) {
InputStream stream = response.getEntity().getContent();
Bitmap b = BitmapFactory.decodeStream(stream);
stream.close();
addToDisk(key, b, getImageType(url));
handler.obtainMessage(Constants.SUCCESS, b).sendToTarget();
return;
}
throw new Exception();
} catch (Exception e) {
} finally {
if(client != null) client.getConnectionManager().shutdown();
}
}
});
}
//接口回调
public interface OnImageLoadedListener {
public void onImage(Bitmap bmp);
}
}