上周为360全景项目引入了图片缓存模块。由于是在Android4.0平台以上运做,出于惯性,都会在设计以前查阅相关资料,尽可能避免拿一些之前2.3平台积累的经验来进行类比处理。开发文档中有一个 BitmapFun的示例,仔细拜读了一下,虽然说围绕着Bitmap的方方面面讲得都很深刻,但感受很难引入到当前项目中去。 如今的图片服务提供者基本上都来源于网络。对于应用平台而言,访问网络属于耗时操做。尤为是在移动终端设备上,它的显著表现为系统的延迟时间变长、用户交互性变差等。能够想象,一个携带着这些问题的应用在市场上是很难与同类产品竞争的。
说明一下,本文借鉴了 Keegan小钢和安卓巴士的处理模板,主要针对的是4.0以上平台应用。2.3之前平台执行效果未知,请斟酌使用或直接略过:),固然更欢迎您把测试结果告知笔者。
1、图片加载流程
首先,咱们谈谈加载图片的流程,项目中的该模块处理流程以下:
1.在UI主线程中,从内存缓存中获取图片,找到后返回。找不到进入下一步;
2.在工做线程中,从磁盘缓存中获取图片,找到即返回并更新内存缓存。找不到进入下一步;
3.在工做线程中,从网络中获取图片,找到即返回并同时更新内存缓存和磁盘缓存。找不到显示默认以提示。 html
2、内存缓存类(PanoMemCache)java
这里使用Android提供的LruCache类,该类保存一个强引用来限制内容数量,每当Item被访问的时候,此Item就会移动到队列的头部。当cache已满的时候加入新的item时,在队列尾部的item会被回收。android
- public class PanoMemoryCache {
-
- // LinkedHashMap初始容量
- private static final int INITIAL_CAPACITY = 16;
- // LinkedHashMap加载因子
- private static final int LOAD_FACTOR = 0.75f;
- // LinkedHashMap排序模式
- private static final boolean ACCESS_ORDER = true;
-
- // 软引用缓存
- private static LinkedHashMap<String, SoftReference<Bitmap>> mSoftCache;
- // 硬引用缓存
- private static LruCache<String, Bitmap> mLruCache;
-
- public PanoMemoryCache() {
- // 获取单个进程可用内存的最大值
- // 方式一:使用ActivityManager服务(计量单位为M)
- /*int memClass = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();*/
- // 方式二:使用Runtime类(计量单位为Byte)
- final int memClass = (int) Runtime.getRuntime().maxMemory();
- // 设置为可用内存的1/4(按Byte计算)
- final int cacheSize = memClass / 4;
- mLruCache = new LruCache<String, Bitmap>(cacheSize) {
- @Override
- protected int sizeOf(String key, Bitmap value) {
- if(value != null) {
- // 计算存储bitmap所占用的字节数
- return value.getRowBytes() * value.getHeight();
- } else {
- return 0;
- }
- }
-
- @Override
- protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
- if(oldValue != null) {
- // 当硬引用缓存容量已满时,会使用LRU算法将最近没有被使用的图片转入软引用缓存
- mSoftCache.put(key, new SoftReference<Bitmap>(oldValue));
- }
- }
- };
-
- /*
- * 第一个参数:初始容量(默认16)
- * 第二个参数:加载因子(默认0.75)
- * 第三个参数:排序模式(true:按访问次数排序;false:按插入顺序排序)
- */
- mSoftCache = new LinkedHashMap<String, SoftReference<Bitmap>>(INITIAL_CAPACITY, LOAD_FACTOR, ACCESS_ORDER) {
- private static final long serialVersionUID = 7237325113220820312L;
- @Override
- protected boolean removeEldestEntry(Entry<String, SoftReference<Bitmap>> eldest) {
- if(size() > SOFT_CACHE_SIZE) {
- return true;
- }
- return false;
- }
- };
- }
-
- /**
- * 从缓存中获取Bitmap
- * @param url
- * @return bitmap
- */
- public Bitmap getBitmapFromMem(String url) {
- Bitmap bitmap = null;
- // 先从硬引用缓存中获取
- synchronized (mLruCache) {
- bitmap = mLruCache.get(url);
- if(bitmap != null) {
- // 找到该Bitmap以后,将其移到LinkedHashMap的最前面,保证它在LRU算法中将被最后删除。
- mLruCache.remove(url);
- mLruCache.put(url, bitmap);
- return bitmap;
- }
- }
-
-
- // 再从软引用缓存中获取
- synchronized (mSoftCache) {
- SoftReference<Bitmap> bitmapReference = mSoftCache.get(url);
- if(bitmapReference != null) {
- bitmap = bitmapReference.get();
- if(bitmap != null) {
- // 找到该Bitmap以后,将它移到硬引用缓存。并从软引用缓存中删除。
- mLruCache.put(url, bitmap);
- mSoftCache.remove(url);
- return bitmap;
- } else {
- mSoftCache.remove(url);
- }
- }
- }
- return null;
- }
-
- /**
- * 添加Bitmap到内存缓存
- * @param url
- * @param bitmap
- */
- public void addBitmapToCache(String url, Bitmap bitmap) {
- if(bitmap != null) {
- synchronized (mLruCache) {
- mLruCache.put(url, bitmap);
- }
- }
- }
-
- /**
- * 清理软引用缓存
- */
- public void clearCache() {
- mSoftCache.clear();
- mSoftCache = null;
- }
- }
补充一点,因为4.0平台之后对SoftReference类引用的对象调整了回收策略,因此该类中的软引用缓存实际上没什么效果,能够去掉。2.3之前平台建议保留。
3、磁盘缓存类(PanoDiskCache) 算法
4、图片工具类(PanoUtils)
1.从网络上获取图片:downloadBitmap() 数组
- /**
- * 从网络上获取Bitmap,并进行适屏和分辨率处理。
- * @param context
- * @param url
- * @return
- */
- public static Bitmap downloadBitmap(Context context, String url) {
- HttpClient client = new DefaultHttpClient();
- HttpGet request = new HttpGet(url);
-
- try {
- HttpResponse response = client.execute(request);
- int statusCode = response.getStatusLine().getStatusCode();
- if(statusCode != HttpStatus.SC_OK) {
- Log.e(TAG, "Error " + statusCode + " while retrieving bitmap from " + url);
- return null;
- }
-
- HttpEntity entity = response.getEntity();
- if(entity != null) {
- InputStream in = null;
- try {
- in = entity.getContent();
- return scaleBitmap(context, readInputStream(in));
- } finally {
- if(in != null) {
- in.close();
- in = null;
- }
- entity.consumeContent();
- }
- }
- } catch (IOException e) {
- request.abort();
- Log.e(TAG, "I/O error while retrieving bitmap from " + url, e);
- } catch (IllegalStateException e) {
- request.abort();
- Log.e(TAG, "Incorrect URL: " + url);
- } catch (Exception e) {
- request.abort();
- Log.e(TAG, "Error while retrieving bitmap from " + url, e);
- } finally {
- client.getConnectionManager().shutdown();
- }
- return null;
- }
2.从输入流读取字节数组,看起来是否是很眼熟啊! 缓存
- public static byte[] readInputStream(InputStream in) throws Exception {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = 0;
- while((len = in.read(buffer)) != -1) {
- out.write(buffer, 0, len);
- }
- in.close();
- return out.toByteArray();
- }
3.对下载的源图片进行适屏处理,这也是必须的:) 网络
- /**
- * 按使用设备屏幕和纹理尺寸适配Bitmap
- * @param context
- * @param in
- * @return
- */
- private static Bitmap scaleBitmap(Context context, byte[] data) {
-
- WindowManager windowMgr = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
- DisplayMetrics outMetrics = new DisplayMetrics();
- windowMgr.getDefaultDisplay().getMetrics(outMetrics);
- int scrWidth = outMetrics.widthPixels;
- int scrHeight = outMetrics.heightPixels;
-
- BitmapFactory.Options options = new BitmapFactory.Options();
- options.inJustDecodeBounds = true;
- Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
- int imgWidth = options.outWidth;
- int imgHeight = options.outHeight;
-
- if(imgWidth > scrWidth || imgHeight > scrHeight) {
- options.inSampleSize = calculateInSampleSize(options, scrWidth, scrHeight);
- }
- options.inJustDecodeBounds = false;
- bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
-
- // 根据业务的须要,在此处还能够进一步作处理
- ...
-
- return bitmap;
- }
-
- /**
- * 计算Bitmap抽样倍数
- * @param options
- * @param reqWidth
- * @param reqHeight
- * @return
- */
- public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
- // 原始图片宽高
- final int height = options.outHeight;
- final int width = options.outWidth;
- int inSampleSize = 1;
-
- if (height > reqHeight || width > reqWidth) {
-
- // 计算目标宽高与原始宽高的比值
- final int heightRatio = Math.round((float) height / (float) reqHeight);
- final int widthRatio = Math.round((float) width / (float) reqWidth);
-
- // 选择两个比值中较小的做为inSampleSize的值
- inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
- if(inSampleSize < 1) {
- inSampleSize = 1;
- }
- }
-
- return inSampleSize;
- }
5、使用decodeByteArray()仍是decodeStream()?
讲到这里,有童鞋可能会问我为何使用BitmapFactory.decodeByteArray(data, 0, data.length, opts)来建立Bitmap,而非使用BitmapFactory.decodeStream(is, null, opts)。你这样作不是要多写一个静态方法readInputStream()吗?
没错,decodeStream()确实是该使用情景下的首选方法,可是在有些情形下,它会致使图片资源不能即时获取,或者说图片被它偷偷地缓存起来,交 还给咱们的时间有点长。可是延迟性是致命的,咱们等不起。因此在这里选用decodeByteArray()获取,它直接从字节数组中获取,贴近于底层 IO、脱离平台限制、使用起来风险更小。
6、引入缓存机制后获取图片的方法 多线程
- /**
- * 加载Bitmap
- * @param url
- * @return
- */
- private Bitmap loadBitmap(String url) {
- // 从内存缓存中获取,推荐在主UI线程中进行
- Bitmap bitmap = memCache.getBitmapFromMem(url);
- if(bitmap == null) {
- // 从文件缓存中获取,推荐在工做线程中进行
- bitmap = diskCache.getBitmapFromDisk(url);
- if(bitmap == null) {
- // 从网络上获取,不用推荐了吧,地球人都知道~_~
- bitmap = PanoUtils.downloadBitmap(this, url);
- if(bitmap != null) {
- diskCache.addBitmapToCache(bitmap, url);
- memCache.addBitmapToCache(url, bitmap);
- }
- } else {
- memCache.addBitmapToCache(url, bitmap);
- }
- }
- return bitmap;
- }
7、工做线程池化
有关多线程的切换问题以及在UI线程中执行loadBitmap()方法无效的问题,请参见另外一篇博文: 使用严苛模式打破Android4.0以上平台应用中UI主线程的“专断专行”。
有关工做线程的处理方式,这里推荐使用定制线程池的方式,核心代码以下: ide
- // 线程池初始容量
- private static final int POOL_SIZE = 4;
- private ExecutorService executorService;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- // 获取当前使用设备的CPU个数
- int cpuNums = Runtime.getRuntime().availableProcessors();
- // 预开启线程池数目
- executorService = Executors.newFixedThreadPool(cpuNums * POOL_SIZE);
-
- ...
- executorService.submit(new Runnable() {
- // 此处执行一些耗时工做,不要涉及UI工做。若是遇到,直接转交UI主线程
- pano.setImage(loadBitmap(url));
- });
- ...
-
- }
咱们知道,线程构造也是比较耗资源的。必定要对其进行有效的管理和维护。千万不要随意而行,一张图片的工做线程不搭理也许没什么,当使用场景变为 ListView和GridView时,线程池化工做就显得尤其重要了。Android不是提供了AsyncTask吗?为何不用它?其实 AsyncTask底层也是靠线程池支持的,它默认分配的线程数是128,是远大于咱们定制的executorService。工具