android Volley框架分析心得

文章分类:APP热点新闻 发布时间:2016-04-28 原文作者:Shi Yongfeng 阅读( )

 
Android网络框架很多,但是基于Google自己的volley,无疑是优秀的一款。
具体可以看本人blog:Volley源码分析(1)----Volley 队列
网络框架,无外乎解决一下几个问题,队列,缓存,图片异步加载,统一的网络请求和处理等。
一.Volley 队列 启动
Volley的队列,首先我们看队列的启动:com.android.volley.toolbox.Volley.java
[Java] 查看源文件 复制代码
?
/**
     * 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) {
        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 = new RequestQueue(new DiskBasedCache(cacheDir), network);
        queue.start();
 
        return queue;
    }


我们依次分析这个方法。这个方法是队列启动的代码。
开始就是获取缓存文件夹,以及userAgent 一些信息。
Build.VERSION.SDK_INT >= 9
会使用HTTPURLConnection作为网络请求,而老的版本就使用httpclient来处理。
关于这2者的区别,很多地方有介绍。HttpUrlConnection是HttpClient轻量级版本。
应该说性能更好,并且足够android平台使用了。
当然,也可以使用自己定义的HttpStack。
Network network = new BasicNetwork(stack);
Network对stack的进一步封装,然后创建队列和启动队列。
com/android/volley/RequestQueue.java:
[Java] 查看源文件 复制代码
?
/**
     * 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] = [/i]networkDispatcher;
            networkDispatcher.start();
        }
    }

启动队列,就是启动了一条cache thread 和4个 network thread。
然后分析CacheDispatcher 和NetworkDispatcher 这两个东东。

二:NetworkDispatcher
这一节我们分析网络请求,所以就忽略cache的部分,将在下一节分析:
public class NetworkDispatcher extends Thread
NetworkDispatcher是一个thread,可见network请求应该是从requestQueue队列中获取数据以后,已while(true)的形式不断的向服务器请求,
当requestQueue 为空时,线程讲block住,直到队列有数据,或者线程推出为止。
com/android/volley/NetworkDispatcher.java:
 run
request默认是存在 PriorityBlockingQueue队列里面,
这个队列 可以解决2个问题。
1)线程间的同步
2)当队列为空时,take方法将会block住。

                // If the request was cancelled already, do not perform the                // network request.                if (request.isCanceled()) {                    request.finish("network-discard-cancelled");                    continue;                }
注释已经解释的很清楚了。
网络请求在这个进行:
[Java] 查看源文件 复制代码
?
NetworkResponse networkResponse = mNetwork.performRequest(request);
                // 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;
                }

是否Modified。
Response<?> response = request.parseNetworkResponse(networkResponse);
把networkResponse转化成Response<?>.
接下去,就是判读是否需要cache,需要就保存此次请求结果。
然后就是分发这次的结果。
以上就是volley的一次网络请求的过程。

三:CacheDispatcher & Cache
首先是com/android/volley/RequestQueue.java
的add 方法。
 add
private final Set<Request<?>> mCurrentRequests 这个集合用于记录当前正在队列里面的request,此处的集合应该是所有的request。
request.setSequence(getSequenceNumber());
用于request的排序。
        if (!request.shouldCache()) {            mNetworkQueue.add(request);            return request;        }
request是否cache,如果否,讲直接放到network队列做请求操作。
[Java] 查看源文件 复制代码
?
// 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;
        }


如果cache队列里面已经有正在处理的request,就无需放入cache队列,直接等待返回结果时,会把所有重复的request加入cache。
下面我们分析cache线程的情况。
我们已经说过,request会在网络请求结束的时候,把可以cache的request放入cache库中。
com/android/volley/CacheDispatcher.java
[Java] 查看源文件 复制代码
?
// 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;
[/color][i][color=#000000]                }


通过cachekey,获取缓存的数据。没有的话,将有network dispatcher来处理。
接下来判断是否过期。
过期有2中状态,软过期,和completely 过期。
completely 过期。直接请求网络。
软过期,先response到前台,然后后台进行更新。
这个就是cache线程在干的事情。
再看看刚才response时如何产生cache数据的。
[Java] 查看源文件 复制代码
?
// Parse the response here on the worker thread.
                Response<?> response = request.parseNetworkResponse(networkResponse);
可以看到居然是由每个request自己来决定如何产生cache数据。
Cache.Entry的获得将在:
[Java] 查看源文件 复制代码
?
com/android/volley/toolbox/HttpHeaderParser.java:
public static Cache.Entry parseCacheHeaders(NetworkResponse response)
中获得。这个方法时公共的,如何以后有自定义请求的时候,可以使用该方法。
自此一个volley的队列已经搭载启动了。
我们只需要把request放入requestQueue就可以了!

原文来自:Shi Yongfeng