Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android Volley小白解析(一)

Android Volley小白解析(一)

編輯:關於Android編程

做安卓一年有余,意識到網絡請求框架算是很重要的一塊,考慮到Volley是谷歌自帶的,決定好好研究研究源碼,去理理邏輯思路

首先呢,Volley去哪裡獲取,看下圖即可,在安卓源碼的frameworks目錄下,然後導入到eclipse中即可去研究了

\

 

使用Volley的第一步,首先要調用Volley.newRequestQueue(context)方法來獲取一個RequestQueue對象,那麼我們自然要從這個方法開始看起了,代碼如下所示

 

    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;
    }

 

以上代碼中做了如下幾件事:

1、創建緩存目錄

File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

getCacheDir()方法用於獲取/data/data//cache目錄,創建volley的目錄,用來做後續的緩存目錄

2、創建對應對應版本的HttpStack實例

 

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));
            }
上面這段代碼是Build.VERSION.SDK_INT是獲取當前手機版本,則創建一個HurlStack的實例,否則就創建一個HttpClientStack的實例。實際上HurlStack的內部就是使用HttpURLConnection進行網絡通訊的,而HttpClientStack的內部則是使用HttpClient進行網絡通訊的
3、Network network = new BasicNetwork(stack);生成自定義的Network對象,看看這個網絡對象的構造函數

 

   public BasicNetwork(HttpStack httpStack) {
        this(httpStack, new ByteArrayPool(DEFAULT_POOL_SIZE));
    }

    public BasicNetwork(HttpStack httpStack, ByteArrayPool pool) {
        mHttpStack = httpStack;
        mPool = pool;
    }
構造函數著重看new ByteArrayPool(DEFAULT_POOL_SIZE),那麼ByteArrayPool這個類做了什麼操作?

在對響應的實體進行操作的時候,使用到了byte[] ,由於volley是輕量級頻次高的網絡請求框架,因此會大量使用到byte[] ,這樣的話會頻繁創建和銷毀byte[]。為了提高性能,volley定義了一個byte[]緩沖池,即ByteArrayPool 。

在ByteArrayPool 內,定義了 兩個集合,

 

  private List mBuffersByLastUse = new LinkedList();
    private List mBuffersBySize = new ArrayList(64);

 

分別是存儲按按使用先後順序排列byte[]的list和大小順序排列byte[]的list 。在volley中所需要使用到的byte[]從該緩沖池中來取,當byte[]使用完畢後再歸還到該緩沖池,從而避免頻繁的創建和銷毀byte[]。

看下ByteArrayPool的如下方法:

getBuf:從池中獲取一個可用的byte[],如果沒有,就創建一個。參數為想要獲取多大長度的byte[]

returnBuf:當使用完一個byte[]後,將該byte[]返回到池中

trim:當現有字節總數超過了設定的界限,那麼需要清理

4、創建RequestQueue對象,在RequestQueue構造方法中,進行如下初始化操作

 

  public RequestQueue(Cache cache, Network network, int threadPoolSize,
            ResponseDelivery delivery) {
        mCache = cache;
        mNetwork = network;
        mDispatchers = new NetworkDispatcher[threadPoolSize];
        mDelivery = delivery;
    }
我們看看初始化操作都做了什麼?

Cache cache =new DiskBasedCache(cacheDir)這個是網絡數據的磁盤緩存

Network network = new BasicNetwork(stack);就是Network類

NetworkDispatcher[] mDispatchers=new NetworkDispatcher[threadPoolSize];就是請求數據的網絡線程

ResponseDelivery mDelivery=new ExecutorDelivery(new Handler(Looper.getMainLooper())volley中默認的響應傳遞類

5、看下queue.start();這個方法,也就是最後一步啟動線程進行數據訪問,我們在RequestQueue看看start做了什麼呢?

Volley最主要的功能其實就是跟網絡打交道,然後從網絡中獲取相對應的數據,如果只有網絡請求線程NetworkDispatcher,沒有緩存線程(CacheDispatcher),顯然不是很理想,所以在queue.start();方法中可以看到

 

    public void start() {
        stop();  
        mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);
        mCacheDispatcher.start();

        for (int i = 0; i < mDispatchers.length; i++) {
            NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,
                    mCache, mDelivery);
            mDispatchers[i] = networkDispatcher;
            networkDispatcher.start();
        }
    }

 

 mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);
        mCacheDispatcher.start();
生成了緩存線程CacheDispatcher,緩存中沒有對應的記錄的話,還是會將其扔到網絡隊列中,由網絡線程(NetworkDispatcher)來干活

到此位置,我們就知道了構造方法中有磁盤緩存DiskBasedCache、Network類、網絡主請求線程mDispatchers、請求結果的相應類ResponseDelivery、以及queue.start()中的網絡緩存線程CacheDispatcher

 

我們之前寫Volley的例子都是這樣操作的:mQueue.add(stringRequest); 之類的操作

 

    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();
            if (mWaitingRequests.containsKey(cacheKey)) {
                // There is already a request in flight. Queue up.
                Queue> stagedRequests = mWaitingRequests.get(cacheKey);
                if (stagedRequests == null) {
                    stagedRequests = new LinkedList>();
                }
                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;
        }
    }

 

可以看到,在!request.shouldCache()來判斷要不要去緩存中查詢,如果是去緩存中查詢,那麼就會把請求放到CacheQueue中,如果沒有設置緩存則在mNetworkQueue.add(request);直接將這條請求加入網絡請求隊列。在默認情況下,每條請求都是可以緩存的,當然我們也可以調用Request的setShouldCache(false)方法來改變這一默認行為。

那麼既然默認每條請求都是可以緩存的,自然就被添加到了緩存隊列中,於是一直在後台等待的緩存線程就要開始運行起來了,

會去調用queue.start();那麼就看看start方法中都干什麼吧,如下:

 

    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();

        for (int i = 0; i < mDispatchers.length; i++) {
            NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,
                    mCache, mDelivery);
            mDispatchers[i] = networkDispatcher;
            networkDispatcher.start();
        }
    }
private static final int DEFAULT_NETWORK_THREAD_POOL_SIZE = 4;

而默認情況下for循環會執行四次,也就是說當調用了Volley.newRequestQueue(context)之後,就會有五個線程一直在後台運行,不斷等待網絡請求的到來,其中1個CacheDispatcher是緩存線程,4個NetworkDispatcher是網絡請求線程。

既然有5個線程運行,我們就先看看CacheDispatcher緩存線程做了什麼操作?

 

	public void run() {
		if (DEBUG)
			VolleyLog.v("start new dispatcher");
		Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

		// 初始化緩存
		mCache.initialize();

		while (true) {
			try {
				// 從緩存隊列中獲取一個請求
				final Request request = mCacheQueue.take();
				request.addMarker("cache-queue-take");

				// 如果請求已經被取消,則重新獲取請求
				if (request.isCanceled()) {
					request.finish("cache-discard-canceled");
					continue;
				}

				// 根據request的cacheKey從緩存中得到對應的記錄
				Cache.Entry entry = mCache.get(request.getCacheKey());
				if (entry == null) {
					request.addMarker("cache-miss");
					// 這裡說明緩存中沒有對應的記錄,那麼需要去網絡中獲取,那麼就將它放到Network的隊列中
					mNetworkQueue.put(request);
					continue;
				}

				// 如果緩存中有記錄,但是已經過期了或者失效了,也需要去網絡獲取,放到Network隊列中
				if (entry.isExpired()) {
					request.addMarker("cache-hit-expired");
					request.setCacheEntry(entry);
					mNetworkQueue.put(request);
					continue;
				}

				// 如果上面的情況都不存在,說明緩存中存在這樣記錄,那麼就調用request的parseNetworkResponse方法,獲取一個響應Response
				request.addMarker("cache-hit");
				Response response = request
						.parseNetworkResponse(new NetworkResponse(entry.data,
								entry.responseHeaders));
				request.addMarker("cache-hit-parsed");

				if (!entry.refreshNeeded()) {
					// 緩存記錄,不需要更新,那麼就直接調用mDelivery,傳回給主線程去更新。
					mDelivery.postResponse(request, response);
				} else {
					// 還存在這樣一種情況,緩存記錄存在,但是它約定的生存時間已經到了(還未完全過期,叫軟過期),可以將其發送到主線程去更新
					// 但同時,也要從網絡中更新它的數據
					request.addMarker("cache-hit-refresh-needed");
					request.setCacheEntry(entry);

					// Mark the response as intermediate.
					response.intermediate = true;

					// 將其傳回主線程的同時,將請求放到Network隊列中。
					mDelivery.postResponse(request, response, new Runnable() {
						@Override
						public void run() {
							try {
								mNetworkQueue.put(request);
							} catch (InterruptedException e) {
								// Not much we can do about this.
							}
						}
					});
				}

			} catch (InterruptedException e) {
				// We may have been interrupted because it was time to quit.
				if (mQuit) {
					return;
				}
				continue;
			}
		}
	}

緩存線程(CacheDispatcher)主要做了幾件事情:

 

 

1)初始化本地緩存

2)開始一個無限的循環,調用 mCacheQueue的take方法,來獲得一個請求,而mCacheQueue是一個BlockingQueue,也就是說,當隊列中沒有請求的時候,take方法就會一直阻塞在這裡,等待隊列中的請求,而一旦隊列中有新的請求進來了,那麼它就會馬上執行下去。

3)判斷請求是否已經取消,如果已經被取消了,則不需要再走下去。

4)根據請求的CacheKey去緩存中尋找相對應的記錄,如果找不到對應的記錄,或者對應的記錄過期了,則將其放到NetworkQueue隊列中。

5)緩存中存在相對應的記錄,那麼調用每個請求具體的實現方法 parseNetworkResponse函數,根據具體的請求去解析得到對應的響應Response對象。

6)獲得Response對象之後,還會再進行判斷這個請求是不是進行一次網絡的更新,這是根據記錄的soft-ttl (time-to-live)屬性

從這裡也可以看到,expired的判斷跟refreshNeed的判斷是兩個字段,一個是ttl,一個是softTtl。

如果需要進行更新,那麼就會在發送響應結果回主線程更新的同時,再將請求放到NetworkQueue中,從網絡中更新請求對應的數據。如果不需要,則直接將結果調用mDelivery傳回主線程進行UI的更新。

 

Volley最主要的功能其實就是跟網絡打交道,然後從網絡中獲取相對應的數據,雖然有緩存線程(CacheDispatcher),但是如果緩存中沒有對應的記錄的話,還是會將其扔到網絡隊列中,由網絡線程(NetworkDispatcher)來干活。

networkDispatcher.start();我們看看網絡線程這裡面做了什麼操作?

 

    @Override
    public void run() {
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        Request request;
        while (true) {
            try {
            	 // 從隊列中獲取一個請求,如果沒有請求,則會一直阻塞  
                request = mQueue.take();
            } catch (InterruptedException e) {
                // We may have been interrupted because it was time to quit.
                if (mQuit) {
                    return;
                }
                continue;
            }

            try {
                request.addMarker("network-queue-take");

             // 判斷請求有沒有取消,如果取消,則不必再繼續  
                if (request.isCanceled()) {
                    request.finish("network-discard-cancelled");
                    continue;
                }

                addTrafficStatsTag(request);

             // 調用mNetwork去跟網絡打交道 
                NetworkResponse networkResponse = mNetwork.performRequest(request);
                request.addMarker("network-http-complete");

             // 如果服務器返回一個未修改(304)的響應,並且這個請求已經發送過響應對象,不需要再繼續,因為沒改過  
                if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                    request.finish("not-modified");
                    continue;
                }

                // 分析響應的數據,返回Response對象  
                Response response = request.parseNetworkResponse(networkResponse);
                request.addMarker("network-parse-complete");

                // 根據request的shouldCache字段來判斷是不是需要緩存,如果需要,則將其放到mCache中。
                if (request.shouldCache() && response.cacheEntry != null) {
                    mCache.put(request.getCacheKey(), response.cacheEntry);
                    request.addMarker("network-cache-written");
                }

             // 調用 mDelivery將Response對象傳回主線程進行UI的更新。
                request.markDelivered();
                mDelivery.postResponse(request, response);
            } catch (VolleyError volleyError) {
            	//有錯誤,也會調用到mDelivery,將錯誤信息傳回到主線程,進行提示  
                parseAndDeliverNetworkError(request, volleyError);
            } catch (Exception e) {
                VolleyLog.e(e, "Unhandled exception %s", e.toString());
                mDelivery.postError(request, new VolleyError(e));
            }
        }
    }

 

網絡線程(NetworkDispatcher)主要做了幾件事情:

1)調用 mQueue的take()方法從隊列中獲取請求,如果沒有請求,則一直阻塞在那裡等待,直到隊列中有新的請求到來。

2)判斷請求有沒有被取消,如果被取消,則重新獲取請求。

3)調用Network對象將請求發送到網絡中,並返回一個 NetworkResponse對象。

4)調用請求的pareseNetworkResonse方法,將NetworkResponse對象解析成相對應的Response對象。

5)判斷請求是否需要緩存,如果需要緩存,則將其Response中cacheEntry對象放到緩存mCache中。

6)調用 mDelivery將Response對象傳到主線程中進行UI更新。

 

可以看到,網絡線程其實是調用 Network對象去實現跟網絡進行溝通的,而在Volley中,默認的Network實現類,則是BasicNetwork類。我們去看下mNetwork.performRequest(request);做了什麼操作?

 

  public NetworkResponse performRequest(Request request) throws VolleyError {
        long requestStart = SystemClock.elapsedRealtime();
        while (true) {
            HttpResponse httpResponse = null;
            byte[] responseContents = null;
            Map responseHeaders = new HashMap();
            try {
            	// 添加頭部信息  
                Map headers = new HashMap();
                addCacheHeaders(headers, request.getCacheEntry());
              //調用HttpStack對象去網絡中獲取數據,返回一個HttpResponse對象
                httpResponse = mHttpStack.performRequest(request, headers);
                StatusLine statusLine = httpResponse.getStatusLine();
                int statusCode = statusLine.getStatusCode();
//               獲取服務器的響應頭 數組,然後轉為Map集合
                responseHeaders = convertHeaders(httpResponse.getAllHeaders());
             // 從響應的狀態行獲取狀態編碼,如果是304(未修改),說明之前已經取過數據了,那麼就直接利用緩存中的數據,構造一個NetworkResonse對象  
                if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
                    return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED,
                            request.getCacheEntry() == null ? null : request.getCacheEntry().data,
                            responseHeaders, true);
                }

                // 有些響應是不帶內容的,比如響應狀態編碼是204的話,添加一個空的byte作為內容,後面好統一處理。  
                if (httpResponse.getEntity() != null) {
                  responseContents = entityToBytes(httpResponse.getEntity());
                } else {
                  // Add 0 byte response as a way of honestly representing a
                  // no-content request.
                  responseContents = new byte[0];
                }

                // if the request is slow, log it.
                long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
                logSlowRequests(requestLifetime, request, responseContents, statusLine);

                if (statusCode < 200 || statusCode > 299) {
                    throw new IOException();
                }
                //構建NetworkResponse對象
                return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
            } catch (SocketTimeoutException e) {
                attemptRetryOnException("socket", request, new TimeoutError());
            } catch (ConnectTimeoutException e) {
                attemptRetryOnException("connection", request, new TimeoutError());
            } catch (MalformedURLException e) {
                throw new RuntimeException("Bad URL " + request.getUrl(), e);
            } catch (IOException e) {
                int statusCode = 0;
                NetworkResponse networkResponse = null;
                if (httpResponse != null) {
                    statusCode = httpResponse.getStatusLine().getStatusCode();
                } else {
                    throw new NoConnectionError(e);
                }
                VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
                if (responseContents != null) {
                    networkResponse = new NetworkResponse(statusCode, responseContents,
                            responseHeaders, false);
                    if (statusCode == HttpStatus.SC_UNAUTHORIZED ||
                            statusCode == HttpStatus.SC_FORBIDDEN) {
                        attemptRetryOnException("auth",
                                request, new AuthFailureError(networkResponse));
                    } else {
                        // TODO: Only throw ServerError for 5xx status codes.
                        throw new ServerError(networkResponse);
                    }
                } else {
                    throw new NetworkError(networkResponse);
                }
            }
        }
    }

 

BasicNetwork做的事情如下:

1)對於已經有緩存的請求,添加其頭部信息

2)調用 HttpStack 對象去網絡中獲取數據,返回httpResonse 對象。

3)根據狀態編碼來返回不同的Response對象,如304(未修改)就返回緩存中的數據,如果不是,則根據響應中的數據,重新構造一個NetworkResponse對象。

4)BasicNetwork實現了重試的機制,如果第一次從網絡獲取失敗,默認會重新再嘗試一次,如果失敗,則會將Error返回,默認的實現類是DefaultRetryPolicy類。

 

在上面的代碼中httpResponse = mHttpStack.performRequest(request, headers);是通過HttpStack對象去請求返回HttpResponse對象,然後在獲取HttpResponse對象的一些信息,然後封裝為NetworkResponse返回給NetworkDispatcher,

我們要看下mHttpStack如何處理網絡請求的?

 

 public HttpResponse performRequest(Request request, Map additionalHeaders)
            throws IOException, AuthFailureError {
        String url = request.getUrl();
        HashMap map = new HashMap();
        map.putAll(request.getHeaders());//默認為null 
        map.putAll(additionalHeaders);//添加頭部,主要是緩存相關的頭部信息  
        if (mUrlRewriter != null) {
            String rewritten = mUrlRewriter.rewriteUrl(url);
            if (rewritten == null) {
                throw new IOException("URL blocked by rewriter: " + url);
            }
            url = rewritten;
        }
        URL parsedUrl = new URL(url);
        HttpURLConnection connection = openConnection(parsedUrl, request);//打開Connection
        for (String headerName : map.keySet()) {
        	//將Map的對象添加到Connection的屬性中
            connection.addRequestProperty(headerName, map.get(headerName));
        }
        //設置connection方法,主要是設置Method屬性和Content(for post/put)  
        setConnectionParametersForRequest(connection, request);
        //設置Http 協議
        ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
        int responseCode = connection.getResponseCode();
        if (responseCode == -1) {
            throw new IOException("Could not retrieve response code from HttpUrlConnection.");
        }
        StatusLine responseStatus = new BasicStatusLine(protocolVersion,
                connection.getResponseCode(), connection.getResponseMessage());
        
        BasicHttpResponse response = new BasicHttpResponse(responseStatus);
        //獲得Response的流,並將其解析成對應的HttpEntity對象,設置給Response.entity字段
        response.setEntity(entityFromConnection(connection));
        for (Entry> header : connection.getHeaderFields().entrySet()) {
            if (header.getKey() != null) {
                Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
                response.addHeader(h);
            }
        }
        return response;
    }


 

HttpURLConnection是Android3.0以後才提供的一個網絡訪問類,而HurlStack類,也正是H(ttp)URL的縮寫,所以這個類,其實就是基於HttpUrlConnection的實現,其步驟如下:

1)從Request中獲得url參數,根據url參數構造URL對象,而URL對象是java提供的獲取網絡資源的一個封裝好的實用類。 2)從URL對象打開Connection,並設置connection的超時,緩存,讓網絡資源寫入等屬性。

 

3)調用方法setConnectionParametersForRequest 來設置 Method屬性,如果是Post或者Put的話,還要設置Content內容。

4)設置Http 協議,這裡基本上是1.1了。 5)獲得Response的流,並將其解析成對應的HttpEntity對象,設置給Response.entity字段,返回給BasicNetwork。
 
在HurlStack類中(BasicHttpResponse extends AbstractHttpMessage implements HttpResponse)

 

BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection));

然後在封裝為HttpResponse對象返回給BasicNetwork對象

在BasicNetwork中在封裝為 return new NetworkResponse(statusCode, responseContents, responseHeaders, false);返回給NetworkDispatcher對象

最後在NetworkDispatcher中,進行 Responseresponse = request.parseNetworkResponse(networkResponse);將請求結果解析成需要的類型,將NetworkResponse解析成Response

下面的代碼拿StringRequest方式說明

 

    protected Response parseNetworkResponse(NetworkResponse response) {
        String parsed;
        try {
            parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        } catch (UnsupportedEncodingException e) {
            parsed = new String(response.data);
        }
        return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
    }

 

 

  public static Cache.Entry parseCacheHeaders(NetworkResponse response) {
        long now = System.currentTimeMillis();

        Map headers = response.headers;

        long serverDate = 0;
        long serverExpires = 0;
        long softExpire = 0;
        long maxAge = 0;
        boolean hasCacheControl = false;

        String serverEtag = null;
        String headerValue;

        headerValue = headers.get("Date");
        if (headerValue != null) {
            serverDate = parseDateAsEpoch(headerValue);
        }

        headerValue = headers.get("Cache-Control");
        if (headerValue != null) {
            hasCacheControl = true;
            String[] tokens = headerValue.split(",");
            for (int i = 0; i < tokens.length; i++) {
                String token = tokens[i].trim();
                if (token.equals("no-cache") || token.equals("no-store")) {
                    return null;
                } else if (token.startsWith("max-age=")) {
                    try {
                        maxAge = Long.parseLong(token.substring(8));
                    } catch (Exception e) {
                    }
                } else if (token.equals("must-revalidate") || token.equals("proxy-revalidate")) {
                    maxAge = 0;
                }
            }
        }

        headerValue = headers.get("Expires");
        if (headerValue != null) {
            serverExpires = parseDateAsEpoch(headerValue);
        }

        serverEtag = headers.get("ETag");

        // Cache-Control takes precedence over an Expires header, even if both exist and Expires
        // is more restrictive.
        if (hasCacheControl) {
            softExpire = now + maxAge * 1000;
        } else if (serverDate > 0 && serverExpires >= serverDate) {
            // Default semantic for Expire header in HTTP specification is softExpire.
            softExpire = now + (serverExpires - serverDate);
        }

        Cache.Entry entry = new Cache.Entry();
        entry.data = response.data;
        entry.etag = serverEtag;
        entry.softTtl = softExpire;
        entry.ttl = entry.softTtl;
        entry.serverDate = serverDate;
        entry.responseHeaders = headers;

        return entry;
    }
然後NetworkDispatcher拿著解析好的 Responseresponse東東, 去mDelivery.postResponse(request, response);進行ui更新操作

 

 

回頭看NetworkDispatcher類run方法中的 mDelivery.postResponse(request, response);如何去更新ui界面的?

請求結果的交付是通過ResponseDelivery接口完成的,它有一個實現類ExecutorDelivery, 主要有postResponse()與postError()兩個方法,分別在請求成功或失敗時將結果提交給請求發起者。

看 mDelivery.postResponse(request, response);方法的具體實現。每post一個response,都會調用ResponseDeliveryRunnable的run()方法。在這個run()方法中,會通過mRequest.deliverResponse(mResponse.result)來傳遞response的result,這個result其實就是已經解析好的響應結果,比如一個表示處理結果的字符串或一個User對象

 

 @Override
    public void postResponse(Request request, Response response) {
        postResponse(request, response, null);
    }

    @Override
    public void postResponse(Request request, Response response, Runnable runnable) {
        request.markDelivered();
        request.addMarker("post-response");
        mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable));
    }

    @Override
    public void postError(Request request, VolleyError error) {
        request.addMarker("post-error");
        Response response = Response.error(error);
        mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, null));
    }

如下是run方法
        public void run() {
            // If this request has canceled, finish it and don't deliver.
            if (mRequest.isCanceled()) {
                mRequest.finish("canceled-at-delivery");
                return;
            }

            // Deliver a normal response or error, depending.
            if (mResponse.isSuccess()) {
                mRequest.deliverResponse(mResponse.result);
            } else {
                mRequest.deliverError(mResponse.error);
            }

            // If this is an intermediate response, add a marker, otherwise we're done
            // and the request can be finished.
            if (mResponse.intermediate) {
                mRequest.addMarker("intermediate-response");
            } else {
                mRequest.finish("done");
            }

            // If we have been provided a post-delivery runnable, run it.
            if (mRunnable != null) {
                mRunnable.run();
            }
       }

 

 

在mRequest.deliverResponse(mResponse.result)方法中,有ImageRequest、JsonRequest、StringRequest請求方式

\

我們就簡單看StringRequest的實現方法,這裡有一個接口去外部實現

 

  protected void deliverResponse(String response) {
        mListener.onResponse(response);
    }
是通過構造方式傳入進來接口、默認是get方式

 

 

   public StringRequest(int method, String url, Listener listener,
            ErrorListener errorListener) {
        super(method, url, errorListener);
        mListener = listener;
    }
    public StringRequest(String url, Listener listener, ErrorListener errorListener) {
        this(Method.GET, url, listener, errorListener);
    }


這裡還有一個問題, 因為更新UI的操作只能在主線程中進行,那麼ResponseDeliveryRunnable的run()方法不能再新起一個線程來執行,而應該在主線程中執行,這個是如何做到的?

 

其實還是用的Handler,Looper,MessageQueue的那套機制。 在Volley初始化一個RequestQueue的時候,會調用RequestQueue的如下構造函數,它構建了一個ExecutorDelivery對象,並把一個與主線程的Looper關聯的一個Handler,大家還記得如下的構造方法沒?

 

	public RequestQueue(Cache cache, Network network, int threadPoolSize) {
		this(cache, network, threadPoolSize, new ExecutorDelivery(new Handler(
				Looper.getMainLooper())));
	}

然後再看下ExecutorDelivery的構造方法, 通過handler的post方法,把ResponseDeliveryRunnable 這個runnable加到了主線程的消息隊列中,所以它的run()方法是在主線程中執行的。

 

 

   public ExecutorDelivery(final Handler handler) {
        // Make an Executor that just wraps the handler.
        mResponsePoster = new Executor() {
            @Override
            public void execute(Runnable command) {
                handler.post(command);
            }
        };
    }

 


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved