Volley源码分析

基本的使用步骤

        // 1, 获取到请求队列
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        // 2, 创建一个Request
        StringRequest stringRequest = new StringRequest("", new com.android.volley.Response.Listener<String>() {
            @Override
            public void onResponse(String s) {

            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        //3,加入请求队列
        requestQueue.add(stringRequest);

源码分析

public static RequestQueue newRequestQueue(Context context) {
        return newRequestQueue(context, (HttpStack)null);
}
//正在创建的方法
public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
        File cacheDir = new File(context.getCacheDir(), "volley");
        String userAgent = "volley/0";

        try {
            String packageName = context.getPackageName();
            PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
            userAgent = packageName + "/" + info.versionCode;
        } catch (NameNotFoundException var6) {
            ;
        }

        if(stack == null) {
            if(VERSION.SDK_INT >= 9) {
                //创建Http HttpURLConnnect实现
                stack = new HurlStack();
            } else {
              //创建Http HttpClient实现
                stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
            }
        }
        //网络封装层
        Network network = new BasicNetwork((HttpStack)stack);
        //创建请求队列
        RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
        queue.start();
        return queue;
}

//start方法
public void start() {
  this.stop();
  //创建一个CacheDispatcher
  this.mCacheDispatcher = new CacheDispatcher(this.mCacheQueue, this.mNetworkQueue, this.mCache, this.mDelivery);
  this.mCacheDispatcher.start();
  //创建多个NetworkDispatcher 默认是4
  for(int i = 0; i < this.mDispatchers.length; ++i) {
        NetworkDispatcher networkDispatcher = new NetworkDispatcher(this.mNetworkQueue, this.mNetwork, this.mCache, this.mDelivery);
        this.mDispatchers[i] = networkDispatcher;
        networkDispatcher.start();
  }
}

** CacheDispatcher 缓存分发器的实现 **

//继承线程类
public class CacheDispatcher extends Thread
  ...

while(true)
{
  //从缓存队列里面去除一个Request
	final Request request = (Request)this.mCacheQueue.take();
	request.addMarker("cache-queue-take");
  //如果请求取消,加入Marker
	if(request.isCanceled()) {
		request.finish("cache-discard-canceled");
	} else {
    //通过CacheKey从缓存去除缓存的数据
		Entry entry = this.mCache.get(request.getCacheKey());
    //下面是一系列异常情况 加入marker
		if(entry == null) {
			request.addMarker("cache-miss");
			this.mNetworkQueue.put(request);
		} else if(entry.isExpired()) {
			request.addMarker("cache-hit-expired");
			request.setCacheEntry(entry);
			this.mNetworkQueue.put(request);
		} else {
			request.addMarker("cache-hit");
      //解析缓存数据
			Response<?> response = request.parseNetworkResponse(new NetworkResponse(entry.data, entry.responseHeaders));
      //下面也是一些异常情况 加入Marker
			request.addMarker("cache-hit-parsed");
			if(entry.refreshNeeded()) {
				request.addMarker("cache-hit-refresh-needed");
				request.setCacheEntry(entry);
				response.intermediate = true;
        //如果需要去刷新最新的数据,加入到网络队列里面
				this.mDelivery.postResponse(request, response, new Runnable() {
					public void run() {
						try {
							CacheDispatcher.this.mNetworkQueue.put(request);
						} catch (InterruptedException var2) {
							;
						}

					}
				});
			} else {
        //直接返回返回的响应
				this.mDelivery.postResponse(request, response);
			}
		}
	}
}

```java
** NetworkDispatcher 缓存分发器的实现 **

```java
//继承线程类
public class NetworkDispatcher extends Thread

...
//从队列里面取出一个request
request = (Request)this.mQueue.take();

{

	request.addMarker("network-queue-take");
	if(request.isCanceled()) {
		request.finish("network-discard-cancelled");
	} else {
		if(VERSION.SDK_INT >= 14) {
			TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
		}
    //从网络层获取到网络请求
		NetworkResponse networkResponse = this.mNetwork.performRequest(request);
		request.addMarker("network-http-complete");
		if(networkResponse.notModified && request.hasHadResponseDelivered()) {
			request.finish("not-modified");
		} else {
      //解析网络请求
			Response<?> response = request.parseNetworkResponse(networkResponse);
			request.addMarker("network-parse-complete");
			if(request.shouldCache() && response.cacheEntry != null) {
				this.mCache.put(request.getCacheKey(), response.cacheEntry);
				request.addMarker("network-cache-written");
			}

			request.markDelivered();
      //返回响应
			this.mDelivery.postResponse(request, response);
		}
	}

}

** add()方法 **

public Request add(Request request)
{
	request.setRequestQueue(this);
	Set var2 = this.mCurrentRequests;
	synchronized(this.mCurrentRequests) {
		this.mCurrentRequests.add(request);
	}

	request.setSequence(this.getSequenceNumber());
	request.addMarker("add-to-queue");
  //如果请求开启缓存加入缓存队列 如果没有开启缓存,直接加入网络请求队列
	if(!request.shouldCache()) {
		this.mNetworkQueue.add(request);
		return request;
	} else {
		Map var7 = this.mWaitingRequests;
		synchronized(this.mWaitingRequests) {
			String cacheKey = request.getCacheKey();
      //重复性判断
			if(this.mWaitingRequests.containsKey(cacheKey)) {
				Queue<Request> stagedRequests = (Queue)this.mWaitingRequests.get(cacheKey);
				if(stagedRequests == null) {
					stagedRequests = new LinkedList();
				}

				((Queue)stagedRequests).add(request);
				this.mWaitingRequests.put(cacheKey, stagedRequests);
				if(VolleyLog.DEBUG) {
					VolleyLog.v("Request for cacheKey=%s is in flight, putting on hold.", new Object[] {cacheKey});
				}
			} else {
				this.mWaitingRequests.put(cacheKey, (Object)null);
				this.mCacheQueue.add(request);
			}
			return request;
		}
	}
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值