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

2019-12-10 18:25:44于丽

这里主要就是初始化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})。