Android 图片加载框架的简单设计

ljqlovelxy 8年前
   <p>目前Android 发展至今优秀的图片加载框架太多,例如: Volley ,Picasso,Imageloader,Glide等等。但是作为程序猿,懂得其中的实现原理还是相当重要的,只有懂得才能更好地使用。于是乎,今天我就简单设计一个网络加载图片框架。主要就是熟悉图片的网络加载机制。</p>    <p>一般来说,一个优秀的 图片加载框架(ImageLoader) 应该具备如下功能:</p>    <ul>     <li> <p>图片压缩</p> </li>     <li> <p>内存缓存</p> </li>     <li> <p>磁盘缓存</p> </li>     <li> <p>图片的同步加载</p> </li>     <li> <p>图片的异步加载</p> </li>     <li> <p>网络拉取</p> </li>    </ul>    <p>那我们就从以上几个方面进行介绍:</p>    <p><strong>1.图片压缩(有效的降低OOM的发生概率)</strong></p>    <p>图片压缩功能我在Bitmap 的高效加载中已经做了介绍这里不多说直接上代码。这里直接抽象一个类用于完成图片压缩功能。</p>    <pre>  <code class="language-java">public class ImageResizer {      private static final String TAG = "ImageResizer";        public ImageResizer() {          super();          // TODO Auto-generated constructor stub      }        public Bitmap decodeSampledBitmapFromResource(Resources res, int resId,              int reqWidth, int reqHeight) {          final BitmapFactory.Options options = new BitmapFactory.Options();          options.inJustDecodeBounds = true;          BitmapFactory.decodeResource(res, resId, options);            options.inSampleSize = calculateInSampleSize(options, reqWidth,                  reqHeight);            options.inJustDecodeBounds = false;          return BitmapFactory.decodeResource(res, resId, options);      }        public Bitmap decodeSampledBitmapFromBitmapFileDescriptor(FileDescriptor fd,              int reqWidth,int reqHeight){          final BitmapFactory.Options options = new BitmapFactory.Options();          options.inJustDecodeBounds = true;            BitmapFactory.decodeFileDescriptor(fd, null, options);            options.inSampleSize = calculateInSampleSize(options, reqWidth,                  reqHeight);            options.inJustDecodeBounds = false;          return BitmapFactory.decodeFileDescriptor(fd, null, options);      }                public int calculateInSampleSize(BitmapFactory.Options options,              int reqWidth, int reqHeight) {            final int width = options.outWidth;          final int height = options.outHeight;            int inSampleSize = 1;          if (height > reqHeight || width > reqWidth) {              final int halfHeight = height / 2;              final int halfWidth = width / 2;              while ((halfHeight / inSampleSize) > reqHeight                      && (halfWidth / inSampleSize) > halfWidth) {                  inSampleSize *= 2;              }          }          return inSampleSize;        }    }</code></pre>    <p><strong>2.内存缓存和磁盘缓存</strong></p>    <p>缓存直接选择 LruCache 和 DiskLruCache 来完成内存缓存和磁盘缓存工作。</p>    <p>首先对其初始化:</p>    <pre>  <code class="language-java">private LruCache<String, Bitmap> mMemoryCache;  private DiskLruCache mDiskLruCache;    public ImageLoader(Context context) {          mContext = context.getApplicationContext();        //分配内存缓存为当前进程的1/8,磁盘缓存容量为50M          int maxMemory = (int) (Runtime.getRuntime().maxMemory() * 1024);          int cacheSize = maxMemory / 8;          mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {                @Override              protected int sizeOf(String key, Bitmap value) {                  return value.getRowBytes() * value.getHeight() / 1024;              }            };            File diskCacheDir = getDiskChaheDir(mContext, "bitmap");          if (!diskCacheDir.exists()) {              diskCacheDir.mkdirs();          }          if (getUsableSpace(diskCacheDir) > DISK_CACHE_SIZE) {              try {                  mDiskLruCache = DiskLruCache.open(diskCacheDir, 1, 1,                          DISK_CACHE_SIZE);                  mIsDiskLruCacheCreated = true;              } catch (IOException e) {                  e.printStackTrace();              }          }      }</code></pre>    <p>创建完毕后,接下来则需要提供方法来视线添加以及获取的功能。首先来看内存缓存。</p>    <pre>  <code class="language-java">private void addBitmapToMemoryCache(String key, Bitmap bitmap) {          if (getBitmapFromMemCache(key) == null) {              mMemoryCache.put(key, bitmap);          }      }        private Bitmap getBitmapFromMemCache(String key) {          return mMemoryCache.get(key);      }</code></pre>    <p>相对来说内存缓存比较简单,而磁盘缓存则复杂的多。磁盘缓存(LruDiskCache)并没有直接提供方法来实现,而是要通过Editor以及Snapshot 来实现对于文件系统的添加以及读取的操作。</p>    <p>首先看一下,Editor,它提供了commit 和 abort 方法来提交和撤销对文件系统的写操作。</p>    <pre>  <code class="language-java">//将下载的图片写入文件系统,实现磁盘缓存      private Bitmap loadBitmapFromHttp(String url, int reqWidth, int reqHeight)              throws IOException {          if (Looper.myLooper() == Looper.getMainLooper()) {              throw new RuntimeException("can not visit network from UI Thread.");          }          if (mDiskLruCache == null)              return null;          String key = hashKeyFormUrl(url);          DiskLruCache.Editor editor = mDiskLruCache.edit(key);          if (editor != null) {              OutputStream outputStream = editor                      .newOutputStream(DISK_CACHE_INDEX);              if (downloadUrlToStream(url, outputStream)) {                  editor.commit();              } else {                  editor.abort();              }            }          mDiskLruCache.flush();          return loadBitmapForDiskCache(url, reqWidth, reqHeight);      }</code></pre>    <p>Snapshot, 通过它可以获取磁盘缓存对象对应的 FileInputStream,但是FileInputStream 无法便捷的进行压缩,所以通过FileDescriptor 来加载压缩后的图片,最后将加载后的bitmap添加到内存缓存中。</p>    <pre>  <code class="language-java">public Bitmap loadBitmapForDiskCache(String url, int reqWidth, int reqHeight)              throws IOException {          if (Looper.myLooper() == Looper.getMainLooper()) {              Log.w(TAG, "load bitmap from UI Thread , it's not recommended");          }          if (mDiskLruCache == null)              return null;          Bitmap bitmap = null;          String key = hashKeyFormUrl(url);          DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key);          if (snapshot != null) {              FileInputStream fileInputStream = (FileInputStream) snapshot                      .getInputStream(DISK_CACHE_INDEX);              FileDescriptor fileDescriptor = fileInputStream.getFD();              bitmap = mImageResizer.decodeSampledBitmapFromBitmapFileDescriptor(                      fileDescriptor, reqWidth, reqHeight);              if (bitmap != null) {                  addBitmapToMemoryCache(key, bitmap);              }          }          return bitmap;      }</code></pre>    <p><strong>3.同步加载</strong></p>    <p>同步加载的方法需要外部在子线程中调用。</p>    <pre>  <code class="language-java">//同步加载      public Bitmap loadBitmap(String uri, int reqWidth, int reqHeight) {          Bitmap bitmap = loadBitmpaFromMemCache(uri);          if (bitmap != null) {              return bitmap;          }          try {              bitmap = loadBitmapForDiskCache(uri, reqWidth, reqHeight);              if (bitmap != null) {                  return bitmap;              }              bitmap = loadBitmapFromHttp(uri, reqWidth, reqHeight);            } catch (IOException e) {              e.printStackTrace();          }          if (bitmap == null && !mIsDiskLruCacheCreated) {              bitmap = downloadBitmapFromUrl(uri);          }          return bitmap;      }</code></pre>    <p>从方法中可以看出工作过程遵循如下几步:</p>    <p>首先尝试从内存缓存中读取图片,接着尝试从磁盘缓存中读取图片,最后才会从网络中拉取。此方法不能再主线程中执行,执行环境的检测是在loadBitmapFromHttp中实现的。</p>    <pre>  <code class="language-java">if (Looper.myLooper() == Looper.getMainLooper()) {              throw new RuntimeException("can not visit network from UI Thread.");          }</code></pre>    <p><strong>4.异步加载</strong></p>    <pre>  <code class="language-java">//异步加载      public void bindBitmap(final String uri, final ImageView imageView,              final int reqWidth, final int reqHeight) {            imageView.setTag(TAG_KEY_URI, uri);          Bitmap bitmap = loadBitmpaFromMemCache(uri);          if (bitmap != null) {              imageView.setImageBitmap(bitmap);              return;          }          Runnable loadBitmapTask = new Runnable() {                @Override              public void run() {                  Bitmap bitmap = loadBitmap(uri, reqWidth, reqHeight);                  if (bitmap != null) {                      LoaderResult result = new LoaderResult(imageView, uri,                              bitmap);                      mMainHandler.obtainMessage(MESSAGE_POST_RESULT, result)                              .sendToTarget();                    }              }          };          THREAD_POOL_EXECUTOR.execute(loadBitmapTask);      }</code></pre>    <p>从bindBitmap的实现来看,bindBitmap 方法会尝试从内存缓存中读取图片,如果读取成功就直接返回结果,否则会在线程池中去调用loadBitmap方法,当图片加载成功后再将图片、图片的地址以及需要绑定的imageView封装成一个LoaderResult对象,然后再通过mMainHandler向主线程发送一个消息,这样就可以在主线程中给imageView设置图片了。</p>    <p>下面来看一下,bindBitmap这个方法中用到的线程池和Handler,首先看一下线程池 THREAD_POOL_EXECUTOR 的实现。</p>    <pre>  <code class="language-java">private static final int CPU_COUNT = Runtime.getRuntime()              .availableProcessors();  private static final int CORE_POOL_SIZE = CPU_COUNT + 1;  private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;  private static final long KEEP_ALIVE = 10L;      private static final ThreadFactory sThreadFactory = new ThreadFactory() {          private final AtomicInteger mCount = new AtomicInteger();            @Override          public Thread newThread(Runnable r) {              // TODO Auto-generated method stub              return new Thread(r, "ImageLoader#" + mCount.getAndIncrement());          }      };      public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(              CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS,              new LinkedBlockingDeque<Runnable>(), sThreadFactory);</code></pre>    <p>1.使用线程池和handler的原因。</p>    <p>首先不能用普通线程去实现,如果采用普通线程去加载图片,随着列表的滑动可能会产生大量的线程,这样不利于效率的提升。 Handler 的实现 ,直接采用了 主线程的Looper来构造Handler 对象,这就使得 ImageLoader 可以在非主线程构造。另外为了解决由于View复用所导致的列表错位这一问题再给ImageView 设置图片之前会检查他的url有没有发生改变,如果发生改变就不再给它设置图片,这样就解决了列表错位问题。</p>    <pre>  <code class="language-java">private Handler mMainHandler = new Handler(Looper.getMainLooper()) {            @Override          public void handleMessage(Message msg) {              LoaderResult result = (LoaderResult) msg.obj;              ImageView imageView = result.imageView;              imageView.setImageBitmap(result.bitmap);              String uri = (String) imageView.getTag(TAG_KEY_URI);              if (uri.equals(result.uri)) {                  imageView.setImageBitmap(result.bitmap);              } else {                  Log.w(TAG, "set image bitmap,but url has changed , ignored!");              }          }        };</code></pre>    <p><strong>总结:</strong></p>    <p>图片加载的问题 ,尤其是大量图片的加载,对于android 开发者来说一直是比较困扰的问题。本文只是提到了最基础的一种解决方法,用于学习还是不错的。</p>    <p> </p>    <p> </p>    <p>来自:http://www.jianshu.com/p/2319b16d269f</p>    <p> </p>