Volley学习笔记---框架源码解读

67 阅读3分钟

###官方Volley工作流程图

###从头看起,从获取一个RequestQueue对象开始

  • 使用Volley的第一步, 首先要调用Volley.newRequestQueue(context)方法 来获取一个RequestQueue对象, Ctrl点击newRequestQueue()查看源码:
    /**
     * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
     *
     * @param context A {@link Context} to use for creating the cache dir.
     * @return A started {@link RequestQueue} instance.
     */
    public static RequestQueue newRequestQueue(Context context) {
        return newRequestQueue(context, null);
    }
  • 这个方法仅仅只有一行代码, 只是调用了newRequestQueue()的方法重载, 并给第二个参数传入null, 下面是带有两个参数的newRequestQueue()方法源码:
    /**
     * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
     *
     * @param context A {@link Context} to use for creating the cache dir.
     * @param stack An {@link HttpStack} to use for the network, or null for default.
     * @return A started {@link RequestQueue} instance.
     */
    public static RequestQueue newRequestQueue(Context context, HttpStack stack)
    {
    	return newRequestQueue(context, stack, -1);
    }
  • 这个方法亦仅有一行代码, 亦只调用了newRequestQueue()的方法重载, 并给第三个参数传入-1, 下面是带有三个参数的newRequestQueue()方法源码:
    /**
     * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
     * You may set a maximum size of the disk cache in bytes.
     *
     * @param context A {@link Context} to use for creating the cache dir.
     * @param stack An {@link HttpStack} to use for the network, or null for default.
     * @param maxDiskCacheBytes the maximum size of the disk cache, in bytes. Use -1 for default size.
     * @return A started {@link RequestQueue} instance.
     */
    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;
    }
  • 可以看到, 这里第一个if判断, 如果stacknull, 则去创建一个HttpStack对象, 这里会判断如果手机系统版本号大于9 则创建一个HurlStack的实例, 否则就创建一个HttpClientStack的实例。 实际上HurlStack的内部就是使用HttpURLConnection进行网络通讯的,而HttpClientStack的内部则是使用HttpClient进行网络通讯的, 关于HttpURLConnection还是HttpClient的选择, 可以参考文章使用HttpURLConnection还是HttpClient?

  • 查看源码,可知HurlStackHttpClientStack都是HttpStack的子类(都implements HttpStack了)

  • 创建好HttpStack之后, 创建了一个Network对象, 它是用于根据传入的HttpStack对象来处理网络请求的, 接着new出一个RequestQueue对象, 并调用它的start()方法进行启动, 最后将RequestQueue返回, 这样newRequestQueue()的方法就执行结束了。 (即, 创建HttpStack,拿去 --- 创建Network,拿去 --- new RequestQueue,最后 --- 调用RequestQueue.start()

##RequestQueue中的start()方法 源码如下:

    /**
     * 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();
        }
    }

    /**
     * Stops the cache and network dispatchers.
     */
    public void stop() {
        if (mCacheDispatcher != null) {
            mCacheDispatcher.quit();
        }
        for (int i = 0; i < mDispatchers.length; i++) {
            if (mDispatchers[i] != null) {
                mDispatchers[i].quit();
            }
        }
    }
  • 这里先是创建一个CacheDispatcher的实例, 然后调用了它的start()方法, 接着在一个for循环里去创建NetworkDispatcher的实例, 并分别调用它们的start()方法。 这里的CacheDispatcherNetworkDispatcher都是继承自Thread的, 而默认情况下for循环会执行四次, 也就是调用Volley.newRequestQueue(context)之后, 就会有五个线程一直在后台运行, 不断等待网络请求的到来, 其中CacheDispatcher缓存线程NetworkDispatcher网络请求线程