欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

深入剖析Android的Volley库中的图片加载功能

程序员文章站 2024-03-31 14:29:34
一、基本使用要点回顾 volley框架在请求网络图片方面也做了很多工作,提供了好几种方法.本文介绍使用imageloader来进行网络图片的加载. imageload...

一、基本使用要点回顾

volley框架在请求网络图片方面也做了很多工作,提供了好几种方法.本文介绍使用imageloader来进行网络图片的加载.
imageloader的内部使用imagerequest来实现,它的构造器可以传入一个imagecache缓存形参,实现了图片缓存的功能,同时还可以过滤重复链接,避免重复发送请求。
下面是imageloader加载图片的实现方法:

public void displayimg(view view){ 
 imageview imageview = (imageview)this.findviewbyid(r.id.image_view); 
 requestqueue mqueue = volley.newrequestqueue(getapplicationcontext()); 
   
 imageloader imageloader = new imageloader(mqueue, new bitmapcache()); 
 
 imagelistener listener = imageloader.getimagelistener(imageview,r.drawable.default_image, r.drawable.default_image); 
 imageloader.get("http://developer.android.com/images/home/aw_dac.png", listener); 
 //指定图片允许的最大宽度和高度 
 //imageloader.get("http://developer.android.com/images/home/aw_dac.png",listener, 200, 200); 
} 

使用imageloader.getimagelistener()方法创建一个imagelistener实例后,在imageloader.get()方法中加入此监听器和图片的url,即可加载网络图片.

下面是使用lrucache实现的缓存类

public class bitmapcache implements imagecache { 
 
 private lrucache<string, bitmap> cache; 
 
 public bitmapcache() { 
  cache = new lrucache<string, bitmap>(8 * 1024 * 1024) { 
   @override 
   protected int sizeof(string key, bitmap bitmap) { 
    return bitmap.getrowbytes() * bitmap.getheight(); 
   } 
  }; 
 } 
 
 @override 
 public bitmap getbitmap(string url) { 
  return cache.get(url); 
 } 
 
 @override 
 public void putbitmap(string url, bitmap bitmap) { 
  cache.put(url, bitmap); 
 } 
} 

最后,别忘记在androidmanifest.xml文件中加入访问网络的权限

<uses-permission android:name="android.permission.internet"/> 

二、源码分析
(一) 初始化volley请求队列

mreqqueue = volley.newrequestqueue(mctx);

主要就是这一行了:

#volley

public static requestqueue newrequestqueue(context context) {
  return newrequestqueue(context, null);
 }

public static requestqueue newrequestqueue(context context, httpstack stack)
 {
  return newrequestqueue(context, stack, -1);
 }
public static requestqueue newrequestqueue(context context, httpstack stack, int maxdiskcachebytes) {
  file cachedir = new file(context.getcachedir(), default_cache_dir);

  string useragent = "volley/0";
  try {
   string packagename = context.getpackagename();
   packageinfo info = context.getpackagemanager().getpackageinfo(packagename, 0);
   useragent = packagename + "/" + info.versioncode;
  } catch (namenotfoundexception e) {
  }

  if (stack == null) {
   if (build.version.sdk_int >= 9) {
    stack = new hurlstack();
   } else {
    // prior to gingerbread, httpurlconnection was unreliable.
    // see: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
    stack = new httpclientstack(androidhttpclient.newinstance(useragent));
   }
  }

  network network = new basicnetwork(stack);

  requestqueue queue;
  if (maxdiskcachebytes <= -1)
  {
   // no maximum size specified
   queue = new requestqueue(new diskbasedcache(cachedir), network);
  }
  else
  {
   // disk cache size specified
   queue = new requestqueue(new diskbasedcache(cachedir, maxdiskcachebytes), network);
  }

  queue.start();

  return queue;
 }

这里主要就是初始化httpstack,对于httpstack在api大于等于9的时候选择httpurlconnetcion,反之则选择httpclient,这里我们并不关注http相关代码。

接下来初始化了requestqueue,然后调用了start()方法。

接下来看requestqueue的构造:

public requestqueue(cache cache, network network) {
  this(cache, network, default_network_thread_pool_size);
 }
public requestqueue(cache cache, network network, int threadpoolsize) {
  this(cache, network, threadpoolsize,
    new executordelivery(new handler(looper.getmainlooper())));
 }
public requestqueue(cache cache, network network, int threadpoolsize,
   responsedelivery delivery) {
  mcache = cache;
  mnetwork = network;
  mdispatchers = new networkdispatcher[threadpoolsize];
  mdelivery = delivery;
 }

初始化主要就是4个参数:mcache、mnetwork、mdispatchers、mdelivery。第一个是硬盘缓存;第二个主要用于http相关操作;第三个用于转发请求的;第四个参数用于把结果转发到ui线程(ps:你可以看到new handler(looper.getmainlooper()))。

接下来看start方法

#requestqueue
 /**
  * starts the dispatchers in this queue.
  */
 public void start() {
  stop(); // make sure any currently running dispatchers are stopped.
  // create the cache dispatcher and start it.
  mcachedispatcher = new cachedispatcher(mcachequeue, mnetworkqueue, mcache, mdelivery);
  mcachedispatcher.start();

  // create network dispatchers (and corresponding threads) up to the pool size.
  for (int i = 0; i < mdispatchers.length; i++) {
   networkdispatcher networkdispatcher = new networkdispatcher(mnetworkqueue, mnetwork,
     mcache, mdelivery);
   mdispatchers[i] = networkdispatcher;
   networkdispatcher.start();
  }
 }

首先是stop,确保转发器退出,其实就是内部的几个线程退出,这里大家如果有兴趣可以看眼源码,参考下volley中是怎么处理线程退出的(几个线程都是while(true){//dosomething})。

接下来初始化cachedispatcher,然后调用start();初始化networkdispatcher,然后调用start();

上面的转发器呢,都是线程,可以看到,这里开了几个线程在帮助我们工作,具体的源码,我们一会在看。

好了,到这里,就完成了volley的初始化的相关代码,那么接下来看初始化imageloader相关源码。

(二) 初始化imageloader

#volleyhelper
mimageloader = new imageloader(mreqqueue, new imagecache()
  {
   private final lrucache<string, bitmap> mlrucache = new lrucache<string, bitmap>(
     (int) (runtime.getruntime().maxmemory() / 10))
   {
    @override
    protected int sizeof(string key, bitmap value)
    {
     return value.getrowbytes() * value.getheight();
    }
   };

   @override
   public void putbitmap(string url, bitmap bitmap)
   {
    mlrucache.put(url, bitmap);
   }

   @override
   public bitmap getbitmap(string url)
   {
    return mlrucache.get(url);
   }
  });

#imageloader

public imageloader(requestqueue queue, imagecache imagecache) {
  mrequestqueue = queue;
  mcache = imagecache;
 }

很简单,就是根据我们初始化的requestqueue和lrucache初始化了一个imageloader。

(三) 加载图片

我们在加载图片时,调用的是:

 # volleyhelper
 getinstance().getimageloader().get(url, new imageloader.imagelistener());

接下来看get方法:

#imageloader
 public imagecontainer get(string requesturl, final imagelistener listener) {
  return get(requesturl, listener, 0, 0);
 }
public imagecontainer get(string requesturl, imagelistener imagelistener,
   int maxwidth, int maxheight) {
  return get(requesturl, imagelistener, maxwidth, maxheight, scaletype.center_inside);
 }
public imagecontainer get(string requesturl, imagelistener imagelistener,
   int maxwidth, int maxheight, scaletype scaletype) {

  // only fulfill requests that were initiated from the main thread.
  throwifnotonmainthread();

  final string cachekey = getcachekey(requesturl, maxwidth, maxheight, scaletype);

  // try to look up the request in the cache of remote images.
  bitmap cachedbitmap = mcache.getbitmap(cachekey);
  if (cachedbitmap != null) {
   // return the cached bitmap.
   imagecontainer container = new imagecontainer(cachedbitmap, requesturl, null, null);
   imagelistener.onresponse(container, true);
   return container;
  }

  // the bitmap did not exist in the cache, fetch it!
  imagecontainer imagecontainer =
    new imagecontainer(null, requesturl, cachekey, imagelistener);

  // update the caller to let them know that they should use the default bitmap.
  imagelistener.onresponse(imagecontainer, true);

  // check to see if a request is already in-flight.
  batchedimagerequest request = minflightrequests.get(cachekey);
  if (request != null) {
   // if it is, add this request to the list of listeners.
   request.addcontainer(imagecontainer);
   return imagecontainer;
  }

  // the request is not already in flight. send the new request to the network and
  // track it.
  request<bitmap> newrequest = makeimagerequest(requesturl, maxwidth, maxheight, scaletype,
    cachekey);

  mrequestqueue.add(newrequest);
  minflightrequests.put(cachekey,
    new batchedimagerequest(newrequest, imagecontainer));
  return imagecontainer;
 }

可以看到get方法,首先通过throwifnotonmainthread()方法限制必须在ui线程调用;

然后根据传入的参数计算cachekey,获取cache;

=>如果cache存在,直接将返回结果封装为一个imagecontainer(cachedbitmap, requesturl),然后直接回调imagelistener.onresponse(container, true);我们就可以设置图片了。

=>如果cache不存在,初始化一个imagecontainer(没有bitmap),然后直接回调,imagelistener.onresponse(imagecontainer, true);,这里为了让大家在回调中判断,然后设置默认图片(所以,大家在自己实现listener的时候,别忘了判断resp.getbitmap()!=null);

接下来检查该url是否早已加入了请求对了,如果早已加入呢,则将刚初始化的imagecontainer加入batchedimagerequest,返回结束。

如果是一个新的请求,则通过makeimagerequest创建一个新的请求,然后将这个请求分别加入mrequestqueue和minflightrequests,注意minflightrequests中会初始化一个batchedimagerequest,存储相同的请求队列。

这里注意mrequestqueue是个对象,并不是队列数据结构,所以我们要看下add方法

#requestqueue
public <t> request<t> add(request<t> request) {
  // tag the request as belonging to this queue and add it to the set of current requests.
  request.setrequestqueue(this);
  synchronized (mcurrentrequests) {
   mcurrentrequests.add(request);
  }

  // process requests in the order they are added.
  request.setsequence(getsequencenumber());
  request.addmarker("add-to-queue");

  // if the request is uncacheable, skip the cache queue and go straight to the network.
  if (!request.shouldcache()) {
   mnetworkqueue.add(request);
   return request;
  }

  // insert request into stage if there's already a request with the same cache key in flight.
  synchronized (mwaitingrequests) {
   string cachekey = request.getcachekey();
   if (mwaitingrequests.containskey(cachekey)) {
    // there is already a request in flight. queue up.
    queue<request<?>> stagedrequests = mwaitingrequests.get(cachekey);
    if (stagedrequests == null) {
     stagedrequests = new linkedlist<request<?>>();
    }
    stagedrequests.add(request);
    mwaitingrequests.put(cachekey, stagedrequests);
    if (volleylog.debug) {
     volleylog.v("request for cachekey=%s is in flight, putting on hold.", cachekey);
    }
   } else {
    // insert 'null' queue for this cachekey, indicating there is now a request in
    // flight.
    mwaitingrequests.put(cachekey, null);
    mcachequeue.add(request);
   }
   return request;
  }
 }

这里首先将请求加入mcurrentrequests,这个mcurrentrequests保存了所有需要处理的request,主要为了提供cancel的入口。

如果该请求不应该被缓存则直接加入mnetworkqueue,然后返回。

然后判断该请求是否有相同的请求正在被处理,如果有则加入mwaitingrequests;如果没有,则
加入mwaitingrequests.put(cachekey, null)和mcachequeue.add(request)。

ok,到这里我们就分析完成了直观的代码,但是你可能会觉得,那么到底是在哪里触发的网络请求,加载图片呢?

那么,首先你应该知道,我们需要加载图片的时候,会makeimagerequest然后将这个请求加入到各种队列,主要包含mcurrentrequests、mcachequeue。

然后,还记得我们初始化requestqueue的时候,启动了几个转发线程吗?cachedispatcher和networkdispatcher。

其实,网络请求就是在这几个线程中真正去加载的,我们分别看一下;

(四)cachedispatcher

看一眼构造方法;

#cachedispatcher
 public cachedispatcher(
   blockingqueue<request<?>> cachequeue, blockingqueue<request<?>> networkqueue,
   cache cache, responsedelivery delivery) {
  mcachequeue = cachequeue;
  mnetworkqueue = networkqueue;
  mcache = cache;
  mdelivery = delivery;
 }


这是一个线程,那么主要的代码肯定在run里面。

#cachedispatcher

 @override
 public void run() {
  if (debug) volleylog.v("start new dispatcher");
  process.setthreadpriority(process.thread_priority_background);

  // make a blocking call to initialize the cache.
  mcache.initialize();

  while (true) {
   try {
    // get a request from the cache triage queue, blocking until
    // at least one is available.
    final request<?> request = mcachequeue.take();
    request.addmarker("cache-queue-take");

    // if the request has been canceled, don't bother dispatching it.
    if (request.iscanceled()) {
     request.finish("cache-discard-canceled");
     continue;
    }

    // attempt to retrieve this item from cache.
    cache.entry entry = mcache.get(request.getcachekey());
    if (entry == null) {
     request.addmarker("cache-miss");
     // cache miss; send off to the network dispatcher.
     mnetworkqueue.put(request);
     continue;
    }

    // if it is completely expired, just send it to the network.
    if (entry.isexpired()) {
     request.addmarker("cache-hit-expired");
     request.setcacheentry(entry);
     mnetworkqueue.put(request);
     continue;
    }

    // we have a cache hit; parse its data for delivery back to the request.
    request.addmarker("cache-hit");
    response<?> response = request.parsenetworkresponse(
      new networkresponse(entry.data, entry.responseheaders));
    request.addmarker("cache-hit-parsed");

    if (!entry.refreshneeded()) {
     // completely unexpired cache hit. just deliver the response.
     mdelivery.postresponse(request, response);
    } else {
     // soft-expired cache hit. we can deliver the cached response,
     // but we need to also send the request to the network for
     // refreshing.
     request.addmarker("cache-hit-refresh-needed");
     request.setcacheentry(entry);

     // mark the response as intermediate.
     response.intermediate = true;

     // post the intermediate response back to the user and have
     // the delivery then forward the request along to the network.
     mdelivery.postresponse(request, response, new runnable() {
      @override
      public void run() {
       try {
        mnetworkqueue.put(request);
       } catch (interruptedexception e) {
        // not much we can do about this.
       }
      }
     });
    }

   } catch (interruptedexception e) {
    // we may have been interrupted because it was time to quit.
    if (mquit) {
     return;
    }
    continue;
   }
  }
 }

ok,首先要明确这个缓存指的是硬盘缓存(目录为context.getcachedir()/volley),内存缓存在imageloader那里已经判断过了。

可以看到这里是个无限循环,不断的从mcachequeue去取出请求,如果请求已经被取消就直接结束;

接下来从缓存中获取:

=>如果没有取到,则加入mnetworkqueue

=>如果缓存过期,则加入mnetworkqueue

否则,就是取到了可用的缓存了;调用request.parsenetworkresponse解析从缓存中取出的data和responseheaders;接下来判断ttl(主要还是判断是否过期),如果没有过期则直接通过mdelivery.postresponse转发,然后回调到ui线程;如果ttl不合法,回调完成后,还会将该请求加入mnetworkqueue。

好了,这里其实就是如果拿到合法的缓存,则直接转发到ui线程;反之,则加入到networkqueue.

接下来我们看networkdispatcher。

(五)networkdispatcher

与cachedispatcher类似,依然是个线程,核心代码依然在run中;

# networkdispatcher
//new networkdispatcher(mnetworkqueue, mnetwork,mcache, mdelivery)

public networkdispatcher(blockingqueue<request<?>> queue,
   network network, cache cache,
   responsedelivery delivery) {
  mqueue = queue;
  mnetwork = network;
  mcache = cache;
  mdelivery = delivery;
 }
@override
 public void run() {
  process.setthreadpriority(process.thread_priority_background);
  while (true) {
   long starttimems = systemclock.elapsedrealtime();
   request<?> request;
   try {
    // take a request from the queue.
    request = mqueue.take();
   } catch (interruptedexception e) {
    // we may have been interrupted because it was time to quit.
    if (mquit) {
     return;
    }
    continue;
   }

   try {
    request.addmarker("network-queue-take");

    // if the request was cancelled already, do not perform the
    // network request.
    if (request.iscanceled()) {
     request.finish("network-discard-cancelled");
     continue;
    }

    addtrafficstatstag(request);

    // perform the network request.
    networkresponse networkresponse = mnetwork.performrequest(request);
    request.addmarker("network-http-complete");

    // if the server returned 304 and we delivered a response already,
    // we're done -- don't deliver a second identical response.
    if (networkresponse.notmodified && request.hashadresponsedelivered()) {
     request.finish("not-modified");
     continue;
    }

    // parse the response here on the worker thread.
    response<?> response = request.parsenetworkresponse(networkresponse);
    request.addmarker("network-parse-complete");

    // write to cache if applicable.
    // todo: only update cache metadata instead of entire record for 304s.
    if (request.shouldcache() && response.cacheentry != null) {
     mcache.put(request.getcachekey(), response.cacheentry);
     request.addmarker("network-cache-written");
    }

    // post the response back.
    request.markdelivered();
    mdelivery.postresponse(request, response);
   } catch (volleyerror volleyerror) {
    volleyerror.setnetworktimems(systemclock.elapsedrealtime() - starttimems);
    parseanddelivernetworkerror(request, volleyerror);
   } catch (exception e) {
    volleylog.e(e, "unhandled exception %s", e.tostring());
    volleyerror volleyerror = new volleyerror(e);
    volleyerror.setnetworktimems(systemclock.elapsedrealtime() - starttimems);
    mdelivery.posterror(request, volleyerror);
   }
  }
 }

看代码前,我们首先想一下逻辑,正常情况下我们会取出请求,让network去请求处理我们的请求,处理完成以后呢:加入缓存,然后转发。

那么看下是不是:

首先取出请求;然后通过mnetwork.performrequest(request)处理我们的请求,拿到networkresponse;接下来,使用request去解析我们的networkresponse。
拿到response以后,判断是否应该缓存,如果需要,则缓存。

最后mdelivery.postresponse(request, response);转发;

ok,和我们的预期差不多。

这样的话,我们的volley去加载图片的核心逻辑就分析完成了,简单总结下:

首先初始化requestqueue,主要就是开启几个dispatcher线程,线程会不断读取请求(使用的阻塞队列,没有消息则阻塞)
当我们发出请求以后,会根据url,imageview属性等,构造出一个cachekey,然后首先从lrucache中获取(这个缓存我们自己构建的,凡是实现imagecache接口的都合法);如果没有取到,则判断是否存在硬盘缓存,这一步是从getcachedir里面获取(默认5m);如果没有取到,则从网络请求;
不过,可以发现的是volley的图片加载,并没有lifo这种策略;貌似对于图片的下载,也是完整的加到内存,然后压缩,这么看,对于巨图、大文件这样的就废了;

看起来还是蛮简单的,不过看完以后,对于如何更好的时候该库以及如何去设计图片加载库还是有很大的帮助的;

如果有兴趣,大家还可以在看源码分析的同时,想想某些细节的实现,比如:

dispatcher都是一些无限循环的线程,可以去看看volley如何保证其关闭的。
对于图片压缩的代码,可以在imagerequest的parsenetworkresponse里面去看看,是如何压缩的。
so on…
最后贴个大概的流程图,方便记忆:

深入剖析Android的Volley库中的图片加载功能