网络通讯框架-Volley源码分析(1)

8 篇文章 0 订阅
5 篇文章 0 订阅
Volley主页:https://android.googlesource.com/platform/frameworks/volley
Volley是Google IO 2013演讲上推荐的网络通讯框架,主要功能如下:
  • JSON、图像等的异步下载
  • 网络请求的排序
  • 网络请求的优先级处理
  • 缓存
  • 多级别取消请求
  • 和Activity生命周期联动(Activity结束时同时取消所有的网络请求)
原来对于图像请求,可能需要通过AsyncTask等级制使用HttpUrlConnection从服务器进行下载,并且有时候屏幕转动,缺少缓存机制,导致多次从网络下载数据,造成不必要的网络请求,这些问题在Volley都会得到方便的解决。
关于Volley如何使用,推荐博文:http://blog.csdn.net/t12x3456/article/details/9221611,接下来我会对源码进行发分析讲解,若有不正确的地方,欢迎各位大牛指出改善。

我们先以最简单的get请求为例进行展开
mQueue = Volley.newRequestQueue(getApplicationContext());
mQueue.add(new JsonObjectRequest(Method.GET, url, null,
            new Listener() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "response : " + response.toString());
                  }
            }, null));
mQueue.start();
这个例子比较简单,就是从网络获取Json请求
涉及到的类包括
  • Volley 创建一个默认的工作池实例
  • RequestQueue 拥有调度者线程池的请求调度队列
1.Volley
public static RequestQueue newRequestQueue(Context context) {
        return newRequestQueue(context, null);
    }

    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) {//因为sdk<9,HttpUrlConnection 不可靠,所以若sdk>=9,则创建HurlStack(基于HttpURLConnection),否则创建HttpClientStack(基于HttpClient)
            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);//创建执行Volley的网络请求对象实例
        RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);//创建拥有调度者线程池的请求调度队列对象实例
        queue.start();//启动请求调度队列
        return queue;
    }

2.RequestQueue 
//在队列里开启调度者
    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();
        }
    }

//停止缓存和网络调度者
public void stop() {
        if (mCacheDispatcher != null) {
            mCacheDispatcher.quit();
        }
        for (int i = 0; i < mDispatchers.length; i++) {
            if (mDispatchers[i] != null) {
                mDispatchers[i].quit();
            }
        }
    }

//将一个请求添加到调度队列里
public Request add(Request 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();//获取缓存Key值,其实就是下载的url
            if (mWaitingRequests.containsKey(cacheKey)) {//如果在等待队列里包含该Key值,则取出该列表,并且将该请求加入该列表
                // 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 {//否则,以null值加入等待队列,并且将该请求加入到缓存队列
                // Insert 'null' queue for this cacheKey, indicating there is now a request in
                // flight.
                mWaitingRequests.put(cacheKey, null);
                mCacheQueue.add(request);
            }
            return request;
        }
    }

 //关闭该请求
    void finish(Request request) {
        // Remove from the set of requests currently being processed.
        synchronized (mCurrentRequests) {
            mCurrentRequests.remove(request);//在当前请求队列里去除该请求
        }

        if (request.shouldCache()) {//如果需要缓存,则在等待队列里去除
            synchronized (mWaitingRequests) {
                String cacheKey = request.getCacheKey();
                Queue<Request> waitingRequests = mWaitingRequests.remove(cacheKey);
                if (waitingRequests != null) {
                    if (VolleyLog.DEBUG) {
                        VolleyLog.v("Releasing %d waiting requests for cacheKey=%s.",
                                waitingRequests.size(), cacheKey);
                    }
                    // Process all queued up requests. They won't be considered as in flight, but
                    // that's not a problem as the cache has been primed by 'request'.
                    mCacheQueue.addAll(waitingRequests);//将去除之后的等待队列添加到缓存队列里
                }
            }
        }
    }

Volley源码下载:http://download.csdn.net/detail/jhg19900321/7049517



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值