Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Volley源碼解讀

Volley源碼解讀

編輯:關於Android編程

Volley的中文翻譯為“齊射、並發”,是在2013年的Google大會上發布的一款Android平台網絡通信庫,具有網絡請求的處理、小圖片的異步加載和緩存等功能,能夠幫助 Android APP 更方便地執行網絡操作,而且更快速高效。Volley可是說是把AsyncHttpClient和Universal-Image-Loader的優點集於了一身,既可以像AsyncHttpClient一樣非常簡單地進行HTTP通信,也可以像Universal-Image-Loader一樣輕松加載網絡上的圖片。除了簡單易用之外,Volley在性能方面也進行了大幅度的調整,它的設計目標就是非常適合去進行數據量不大,但通信頻繁的網絡操作,而對於大數據量的網絡操作,比如說下載文件等,Volley的表現就會非常糟糕。

在Google IO的演講上,其配圖是一幅發射火弓箭的圖,有點類似流星。這表示,Volley特別適合數據量不大但是通信頻繁的場景。見下圖:
這裡寫圖片描述

 

Volley特點

自動調度網絡請求;

Volley直接new 5個線程(默認5個),讓多個線程去搶奪網絡請求對象(Request),搶到就執行,搶不到就等待,直到有網絡請求到來。

可以加載圖片;

通過標准的 HTTP cache coherence(高速緩存一致性)緩存磁盤和內存透明的響應;

支持指定請求的優先級;

根據優先級去請求數據

網絡請求cancel機制。我們可以取消單個請求,或者指定取消請求隊列中的一個區域;

例如Activity finish後結束請求 框架容易被定制,例如,定制重試或者網絡請求庫;
例如基於Okhttp的Volley

Volley執行流程

這裡寫圖片描述
 <喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxoMyBpZD0="volley初始化">Volley初始化

創建RequestQueue

使用Volley時我們需要先創建一個RequestQueue,如下

RequestQueue queue = Volley.newRequestQueue(context);

Volley.newRequestQueue(context)最終調用了如下方法

    public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
        File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
        ...
        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;
    }

HttpStack 是一個接口,主要用於請求網絡數據,並返回結果。默認情況下stack是null,
當android版本>=9時使用HurlStack,否則使用HttpClientStack
若用戶想要使用其他的網絡請求類庫,比如okhttp等就可以實現HttpStack接口,並在

HttpResponse performRequest(Request request, Map additionalHeaders)
    throws IOException, AuthFailureError

中調用okhttp進行網絡請求,並把請求的結果封裝成一個
HttpResponse返回即可,HttpResponse中包含了狀態碼,響應頭,body信息。

newRequestQueue中創建了一個BasicNetwork對象,BasicNetwork使用HttpStack執行網絡請求,成功後返回一個NetworkResponse,NetworkResponse只是一個簡單的記錄狀態碼,body,響應頭,服務端是否返回304並且緩存過,執行網絡請求時間的類。

 

DiskBasedCache

newRequestQueue 中還創建了一個 RequestQueue,RequestQueue 中持有一個 DiskBasedCache 對象,
DiskBasedCache 是把服務端返回的數據保持到本地文件中的類,默認大小5M。
緩存文件是一個二進制文件,非文本文件,
緩存文件的開頭有個特殊的整型魔數(CACHE_MAGIC),用於判斷是不是緩存文件。DiskBasedCache 初始化時會
讀取特定文件夾下的所有文件,若文件開頭魔數不是 CACHE_MAGIC 則刪除。是的話就把讀取的數據保存到內存中。代碼如下

public synchronized void initialize() {
        if (!mRootDirectory.exists()) {

            return;
        }

        File[] files = mRootDirectory.listFiles();
        if (files == null) {
            return;
        }
        for (File file : files) {
            BufferedInputStream fis = null;
            try {
                fis = new BufferedInputStream(new FileInputStream(file));
                CacheHeader entry = CacheHeader.readHeader(fis);
                entry.size = file.length();
                putEntry(entry.key, entry);
            } catch (IOException e) {
                if (file != null) {
                    file.delete();
                }
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                } catch (IOException ignored) { }
            }
        }
    }

緩存文件除了可以保存 int,long 型數據,還可以保存 String 字符串,Map

    static String readString(InputStream is) throws IOException {
        int n = (int) readLong(is);
        byte[] b = streamToBytes(is, n);
        return new String(b, "UTF-8");
    }
    static Map readStringStringMap(InputStream is) throws IOException {
        int size = readInt(is);
        Map result = (size == 0)
        ? Collections.emptyMap()
        : new HashMap(size);
        for (int i = 0; i < size; i++) {
            String key = readString(is).intern();
            String value = readString(is).intern();
            result.put(key, value);
        }
        return result;
    }
    static long readLong(InputStream is) throws IOException {
        long n = 0;
        n |= ((read(is) & 0xFFL) << 0);
        n |= ((read(is) & 0xFFL) << 8);
        n |= ((read(is) & 0xFFL) << 16);
        n |= ((read(is) & 0xFFL) << 24);
        n |= ((read(is) & 0xFFL) << 32);
        n |= ((read(is) & 0xFFL) << 40);
        n |= ((read(is) & 0xFFL) << 48);
        n |= ((read(is) & 0xFFL) << 56);
        return n;
    }

緩存文件名由cache key字符串的前半段字符串的hashCode拼接上cache key(網絡請求url)後
半段字符串的hashCode值組成。代碼如下

private String getFilenameForKey(String key) {
        int firstHalfLength = key.length() / 2;
        String localFilename = String.valueOf(key.substring(0, firstHalfLength).hashCode());
        localFilename += String.valueOf(key.substring(firstHalfLength).hashCode());
        return localFilename;
    }

當緩存文件占用空間超過指定值時,Volley只是簡單的刪除的部分文件,刪除代碼如下

private void pruneIfNeeded(int neededSpace) {
        if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes) {
            return;
        }

        Iterator> iterator = mEntries.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = iterator.next();
            CacheHeader e = entry.getValue();
            boolean deleted = getFileForKey(e.key).delete();
            if (deleted) {
                mTotalSize -= e.size;
            } 
            iterator.remove();

            if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes * 0.9f) {
                break;
            }
        }
    }

可以看到刪除時只是遍歷mEntries,如果刪除成功並且剩余文件所占大小+新的緩存所需空間

CacheDispatcherNetworkDispatcher

RequestQueue 只是一個普通的類,沒有繼承任何類,RequestQueue 的 start 方法中創建了一個 CacheDispatcher,和4個(默認4個)NetworkDispatcher,
CacheDispatcher 和 NetworkDispatcher 都是 Thread 的直接子類,這5個 Thread 就是前面提到的搶奪網絡請求對象的 Thread。
調用start()時先調用了一下stop(),stop()中把5個線程的mQuit設為 true,然後調用interrupt()讓 Thread 的run不再執行。
代碼如下

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



        mCache.initialize();
         while (true) {
            try {
              // Get a request from the cache triage queue, blocking until
              // at least one is available.
                final Request request = mCacheQueue.take();

                ...

            }
        }
    }
 /**
     * 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啟動後先調用了一下DiskBasedCache的initialize()方法,這個方法要讀取文件,比較耗時,Volley把他放到了Cache線程中。

CacheDispatcher和NetworkDispatcher的run方法內部很像,都是在 while (true)循環中從PriorityBlockingQueue中讀取Request,PriorityBlockingQueue是一個阻塞隊列,當隊列裡沒有Request時take()方法就會阻塞,直到有Request到來,PriorityBlockingQueue是線程安全的

同一個 Request 只能被5個線程中的一個獲取到。PriorityBlockingQueue 可以根據線程優先級對隊列裡的reqest進行排序。

Volley 的初始化到這就完成了,下面開始執行網絡請求

 

Request

使用 Volley 進行網絡請求時我們要把請求封裝成一個 Request 對象,包括url,請求參數,請求成功失敗 Listener,
Volley 默認給我們提供了 ImageRequest(獲取圖片),
JsonObjectRequest、JsonArrayRequest(獲取json),StringRequest(獲取 String)。
例如:

Requestrequest=new StringRequest(Method.GET, "http://mogujie.com", new  Listener(){
        @Override
        public void onResponse(String response) {
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
        }
    });
    Volley.newRequestQueue(context).add(request);

只需要把Request丟進requestQueue中就可以。

加入RequestQueue

我們來看一下add方法:

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

add方法中首先設置了request所在的請求隊列,為了在用戶取消請求時能夠把request從requestQueue中移除掉。
接下來設置了一下request的序列號,序列號按添加順序依次從0開始編號,同一個隊列中任何兩個request的序列號都不相同。序列號可以影響request的優先級。
request.addMarker(“”)用於調試(打印日志等)。
通過查看源碼我們可以看到request默認是需要緩存的。

/** Whether or not responses to this request should be cached. */
    private boolean mShouldCache = true;

若request不需要緩存則直接把request丟到mNetworkQueue,然後4個 NetworkDispatcher 就可以”搶奪”request了,誰”搶”到誰就執行網絡請求
如需要緩存則先判斷一下mWaitingRequests中有沒有正在請求的相同的request(根據request的url判斷),沒有的話就把該request丟到mCacheQueue中,
這樣 CacheDispatcher 執行完之前的請求後就可以執行該request了,若已經有相同的request正在執行,則只需保存一下該request,
等相同的request執行完後直接使用其結果就可。

CacheDispatcher中獲取到request後先判斷一下request後有沒有取消,有的話就finish掉自己,然後等待下一個request的到來

 if (request.isCanceled()) {
        request.finish("cache-discard-canceled");
        continue;
    }

接下來會從緩存中取緩存,沒有或者緩存已經過期,就把request丟掉mNetworkQueue中,讓mNetworkQueue去“搶奪”request

 // 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;
    }
      // If it is completely expired, just send it to the network.
    if (entry.isExpired()) {
        request.addMarker("cache-hit-expired");
        request.setCacheEntry(entry);
        mNetworkQueue.put(request);
        continue;
    }

若取到緩存且沒過期,則解析緩存。

“`java
Responseresponse = request.parseNetworkResponse(
new NetworkResponse(entry.data, entry.responseHeaders));

“`
若不需要刷新則把request和response丟到ui線程中,回調request中的請求成功或失敗listener,同時finish自己
若還需要刷新的話還需要把request丟到mNetworkQueue中,讓NetworkDispatcher去獲取數據。
NetworkDispatcher在獲取到數據後執行了如下代碼:

// TODO: Only update cache metadata instead of entire record for 304s.
    if (request.shouldCache() && response.cacheEntry != null) {
        mCache.put(request.getCacheKey(), response.cacheEntry);
        request.addMarker("network-cache-written");
    }

CacheDispatcher 才是處理緩存相關的,為什麼 NetworkDispatcher 中還需要進行以上的判斷呢?

回到目錄

 

Request#finish自己

前面我們提到過 CacheDispatcher 把相同的request放到了隊列中,當獲取到數據後調用了request的finish方法,該方法又調用了
mRequestQueue的finish方法。

 void finish(final String tag) {
        if (mRequestQueue != null) {
            mRequestQueue.finish(this);
        }
        ...
    }

request的finish方法如下:

 void finish(Request request) {

        ...
        if (request.shouldCache()) {
            synchronized (mWaitingRequests) {
                String cacheKey = request.getCacheKey();
                Queue> 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);
                }
            }
        }
    }
}

finish中取出了相同的request所在的隊列,然後把請求丟到了mCacheQueue中,丟到mCacheQueue後就會導致 CacheDispatcher 去執行網絡請求,
這時由於上次的請求已經緩存了,所以可以直接使用上傳的數據了,到此為止request如何finish自己就介紹完了。

回到目錄

 

緩存處理

HttpHeaderParser.parseCacheHeaders
處理字符串(分割等)得到響應頭,並把響應頭,body包裝到Cache.Entry中返回。

 

回到目錄

 

Request請求失敗重試機制

Volley的請求重試機制是在Request中設置的,這樣的好處是每一個Request都可以有自己的重試機制,代碼如下

  /**
     * Creates a new request with the given method (one of the values from {@link Method}),
     * URL, and error listener.  Note that the normal response listener is not provided here as
     * delivery of responses is provided by subclasses, who have a better idea of how to deliver
     * an already-parsed response.
     */
    public Request(int method, String url, Response.ErrorListener listener) {
        mMethod = method;
        mUrl = url;
        mErrorListener = listener;
        setRetryPolicy(new DefaultRetryPolicy());

        mDefaultTrafficStatsTag = findDefaultTrafficStatsTag(url);
    }

Request#setRetryPolicy中只是記錄了一下RetryPolicy

/**
     * Sets the retry policy for this request.
     *
     * @return This Request object to allow for chaining.
     */
    public Request setRetryPolicy(RetryPolicy retryPolicy) {
        mRetryPolicy = retryPolicy;
        return this;
    }

DefaultRetryPolicy實現了RetryPolicy接口,根據接口我們可以看到DefaultRetryPolicy可以提供當前超時時間,當前重試次數等


/**
 * Retry policy for a request.
 */
public interface RetryPolicy {

    /**
     * Returns the current timeout (used for logging).
     */
    public int getCurrentTimeout();

    /**
     * Returns the current retry count (used for logging).
     */
    public int getCurrentRetryCount();

    /**
     * Prepares for the next retry by applying a backoff to the timeout.
     * @param error The error code of the last attempt.
     * @throws VolleyError In the event that the retry could not be performed (for example if we
     * ran out of attempts), the passed in error is thrown.
     */
    public void retry(VolleyError error) throws VolleyError;
}

BasicNetwork中performRequest中請求失敗(SocketTimeoutException,ConnectTimeoutException等)時會再次請求一次(默認重試一次)
若還是失敗就會拋出VolleyError異常
具體代碼如下:

public NetworkResponse performRequest(Request request) throws VolleyError {
        ...
        while (true) {
            ...
            try {
                ...
                httpResponse = mHttpStack.performRequest(request, headers);
                ...
                return new NetworkResponse(statusCode, responseContents, responseHeaders, false,
                    SystemClock.elapsedRealtime() - requestStart);
            } 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) {
                ...
            }
        }
    }

attemptRetryOnException代碼如下:

 private static void attemptRetryOnException(String logPrefix, Request request,
            VolleyError exception) throws VolleyError {
        RetryPolicy retryPolicy = request.getRetryPolicy();
        int oldTimeout = request.getTimeoutMs();

        try {
            retryPolicy.retry(exception);
        } catch (VolleyError e) {
            request.addMarker(
                    String.format("%s-timeout-giveup [timeout=%s]", logPrefix, oldTimeout));
            throw e;
        }
        request.addMarker(String.format("%s-retry [timeout=%s]", logPrefix, oldTimeout));
    }

request.getRetryPolicy()得到的是DefaultRetryPolicy類,DefaultRetryPolicy中retry方法

    public void retry(VolleyError error) throws VolleyError {
        mCurrentRetryCount++;
        mCurrentTimeoutMs += (mCurrentTimeoutMs * mBackoffMultiplier);
        if (!hasAttemptRemaining()) {
            throw error;
        }
    }

    //Returns true if this policy has attempts remaining, false otherwise.
    protected boolean hasAttemptRemaining() {
        return mCurrentRetryCount <= mMaxNumRetries;
    }

request.getRetryPolicy() 得到的是 DefaultRetryPolicy 對象,request重試次數超過規定的次數時
attemptRetryOnException 就會拋出 VolleyError,從而導致 performRequest() 方法中 while
循環終止,同時繼續向上拋異常。

PoolingByteArrayOutputStream & ByteArrayPool

為了避免讀取服務端數據時反復的內存申請,Volley提供了PoolingByteArrayOutputStream和ByteArrayPool。

我們先看一下PoolingByteArrayOutputStream的父類ByteArrayOutputStream

/**
     * The byte array containing the bytes written.
     */
    protected byte[] buf;

    /**
     * The number of bytes written.
     */
    protected int count;

ByteArrayOutputStream中提供了兩個protected 的byte[] buf 和 int count,buf用於write時保存數據,count記錄buf已使用的大小,因為都是protected,所有在子類中可以對其進行修改。

我們來看一下ByteArrayOutputStream的write方法,可以看到write中調用了擴展buf大小的expand方法,再來看一下expand的具體實現

  private void expand(int i) {
        /* Can the buffer handle @i more bytes, if not expand it */
        if (count + i <= buf.length) {
            return;
        }

        byte[] newbuf = new byte[(count + i) * 2];
        System.arraycopy(buf, 0, newbuf, 0, count);
        buf = newbuf;
    }

可以看到當已使用的空間+要寫入的大小>buf大小時,直接new 了一個兩倍大小的空間,並把原來的buf中的數據復制到了新的空間中,最後把新分配的空間賦值給了buf,原來的buf由於沒有被任何對象持有,最終會被回收掉。PoolingByteArrayOutputStream就是在重寫的expand對buf進行了處理。

 @Override
    public synchronized void write(byte[] buffer, int offset, int len) {
        Arrays.checkOffsetAndCount(buffer.length, offset, len);
        if (len == 0) {
            return;
        }
        expand(len);
        System.arraycopy(buffer, offset, buf, this.count, len);
        this.count += len;
    }

    /**
     * Writes the specified byte {@code oneByte} to the OutputStream. Only the
     * low order byte of {@code oneByte} is written.
     *
     * @param oneByte
     *            the byte to be written.
     */
    @Override
    public synchronized void write(int oneByte) {
        if (count == buf.length) {
            expand(1);
        }
        buf[count++] = (byte) oneByte;
    }

接下來我們看一下PoolingByteArrayOutputStream是怎麼復用內存空間的。

在執行網絡請求的BasicNetwork我們看到new 了一個ByteArrayPool

 /**
     * @param httpStack HTTP stack to be used
     */
    public BasicNetwork(HttpStack httpStack) {
        // If a pool isn't passed in, then build a small default pool that will give us a lot of
        // benefit and not use too much memory.
        this(httpStack, new ByteArrayPool(DEFAULT_POOL_SIZE));
    }

我們看一下ByteArrayPool的構造函數

 /** The buffer pool, arranged both by last use and by buffer size */
    private List mBuffersByLastUse = new LinkedList();
    private List mBuffersBySize = new ArrayList(64);

 /**
     * @param sizeLimit the maximum size of the pool, in bytes
     */
    public ByteArrayPool(int sizeLimit) {
        mSizeLimit = sizeLimit;
    }

可以看到ByteArrayPool只是記錄了一下最大的內存池空間,默認是4096 bytes,並創建了兩個保存byte[]數組的List。

我們從BasicNetwork中看到讀取服務端數據時調用了entityToBytes方法

  /** Reads the contents of HttpEntity into a byte[]. */
    private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
        PoolingByteArrayOutputStream bytes =
                new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
        byte[] buffer = null;
        try {
            InputStream in = entity.getContent();
            if (in == null) {
                throw new ServerError();
            }
            buffer = mPool.getBuf(1024);
            int count;
            while ((count = in.read(buffer)) != -1) {
                bytes.write(buffer, 0, count);
            }
            return bytes.toByteArray();
        } finally {
            try {
                // Close the InputStream and release the resources by "consuming the content".
                entity.consumeContent();
            } catch (IOException e) {
                // This can happen if there was an exception above that left the entity in
                // an invalid state.
                VolleyLog.v("Error occured when calling consumingContent");
            }
            mPool.returnBuf(buffer);
            bytes.close();
        }
    }

entityToBytes中又new 了一個PoolingByteArrayOutputStream,PoolingByteArrayOutputStream是繼承自java.io.ByteArrayOutputStream的。我們看一下PoolingByteArrayOutputStream構造函數

 /**
     * Constructs a new {@code ByteArrayOutputStream} with a default size of {@code size} bytes. If
     * more than {@code size} bytes are written to this instance, the underlying byte array will
     * expand.
     *
     * @param size initial size for the underlying byte array. The value will be pinned to a default
     *        minimum size.
     */
    public PoolingByteArrayOutputStream(ByteArrayPool pool, int size) {
        mPool = pool;
        buf = mPool.getBuf(Math.max(size, DEFAULT_SIZE));
    }

PoolingByteArrayOutputStream構造函數中調用了mPool.getBuf並賦值給了父類的buf,所以以後調用write時都是把數據寫到了mPool.getBuf得到的byte[]數組中,也就是byte[]池中。getBuf代碼如下:

 /**
     * Returns a buffer from the pool if one is available in the requested size, or allocates a new
     * one if a pooled one is not available.
     *
     * @param len the minimum size, in bytes, of the requested buffer. The returned buffer may be
     *        larger.
     * @return a byte[] buffer is always returned.
     */
    public synchronized byte[] getBuf(int len) {
        for (int i = 0; i < mBuffersBySize.size(); i++) {
            byte[] buf = mBuffersBySize.get(i);
            if (buf.length >= len) {
                mCurrentSize -= buf.length;
                mBuffersBySize.remove(i);
                mBuffersByLastUse.remove(buf);
                return buf;
            }
        }
        return new byte[len];
    }

由於內存池是被多個NetworkDispatcher公用的,所以getBuf前加了synchronized,getBuf就是從byte[]池中找一個滿足大小的空間返回,並從List移除掉,若沒有足夠大的則new一個。再來看一下PoolingByteArrayOutputStream的write方法

 @Override
    public synchronized void write(byte[] buffer, int offset, int len) {
        expand(len);
        super.write(buffer, offset, len);
    }

    @Override
    public synchronized void write(int oneByte) {
        expand(1);
        super.write(oneByte);
    }

可以看到write中調用了expand方法,這個方法不是ByteArrayOutputStream中的,而是PoolingByteArrayOutputStream重寫的,現在看一下expand方法

 /**
     * Ensures there is enough space in the buffer for the given number of additional bytes.
     */
    private void expand(int i) {
        /* Can the buffer handle @i more bytes, if not expand it */
        if (count + i <= buf.length) {
            return;
        }
        byte[] newbuf = mPool.getBuf((count + i) * 2);
        System.arraycopy(buf, 0, newbuf, 0, count);
        mPool.returnBuf(buf);
        buf = newbuf;
    }

expand中沒有調用父類的expand方法,其與父類expand方法的卻別就是由每次的new byte[]變成了從byte[]池中獲取。

在entityToBytes方法中我們看到用完之後又調用了mPool.returnBuf(buffer);把byte[]歸還給了byte[]池,代碼如下:

 /**
     * Returns a buffer to the pool, throwing away old buffers if the pool would exceed its allotted
     * size.
     *
     * @param buf the buffer to return to the pool.
     */
    public synchronized void returnBuf(byte[] buf) {
        if (buf == null || buf.length > mSizeLimit) {
            return;
        }
        mBuffersByLastUse.add(buf);
        int pos = Collections.binarySearch(mBuffersBySize, buf, BUF_COMPARATOR);
        if (pos < 0) {
            pos = -pos - 1;
        }
        mBuffersBySize.add(pos, buf);
        mCurrentSize += buf.length;
        trim();
    }

    /**
     * Removes buffers from the pool until it is under its size limit.
     */
    private synchronized void trim() {
        while (mCurrentSize > mSizeLimit) {
            byte[] buf = mBuffersByLastUse.remove(0);
            mBuffersBySize.remove(buf);
            mCurrentSize -= buf.length;
        }
    }

 

Volley加載圖片

Volley除了可以獲取json還可以加載圖片,用法如下:

ImageRequest imageRequest = new ImageRequest(url,  
        new Response.Listener() {  
            @Override  
            public void onResponse(Bitmap response) {  
                imageView.setImageBitmap(response);  
            }  
        }, 0, 0, Config.RGB_565, new Response.ErrorListener() {  
            @Override  
            public void onErrorResponse(VolleyError error) {  
                imageView.setImageResource(R.drawable.default_image);  
            }  
        }); 

ImageRequest的構造函數接收6個參數,第一個參數就是圖片的URL地址。第二個參數是圖片請求成功的回調,這裡我們把返回的Bitmap參數設置到ImageView中。第三第四個參數分別用於指定允許圖片最大的寬度和高度,如果指定的網絡圖片的寬度或高度大於這裡的最大值,則會對圖片進行壓縮,指定成0的話就表示不管圖片有多大,都不會進行壓縮。第五個參數用於指定圖片的顏色屬性,Bitmap.Config下的幾個常量都可以在這裡使用,其中ARGB_8888可以展示最好的顏色屬性,每個圖片像素占據4個字節的大小,而RGB_565則表示每個圖片像素占據2個字節大小。第六個參數是圖片請求失敗的回調,這裡我們當請求失敗時在ImageView中顯示一張默認圖片。

ImageRequest默認采用GET方式獲取圖片,采用ScaleType.CENTER_INSIDE方式縮放圖片

 public ImageRequest(String url, Response.Listener listener, int maxWidth, int maxHeight,
            ScaleType scaleType, Config decodeConfig, Response.ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        setRetryPolicy(new DefaultRetryPolicy(DEFAULT_IMAGE_TIMEOUT_MS, DEFAULT_IMAGE_MAX_RETRIES,
                DEFAULT_IMAGE_BACKOFF_MULT));
        mListener = listener;
        mDecodeConfig = decodeConfig;
        mMaxWidth = maxWidth;
        mMaxHeight = maxHeight;
        mScaleType = scaleType;
    }

    /**
     * For API compatibility with the pre-ScaleType variant of the constructor. Equivalent to
     * the normal constructor with {@code ScaleType.CENTER_INSIDE}.
     */
    @Deprecated
    public ImageRequest(String url, Response.Listener listener, int maxWidth, int maxHeight,
            Config decodeConfig, Response.ErrorListener errorListener) {
        this(url, listener, maxWidth, maxHeight,
                ScaleType.CENTER_INSIDE, decodeConfig, errorListener);
    }

我們來看一下ImageRequest具體執行邏輯

  @Override
    protected Response parseNetworkResponse(NetworkResponse response) {
        // Serialize all decode on a global lock to reduce concurrent heap usage.
        synchronized (sDecodeLock) {
            try {
                return doParse(response);
            } catch (OutOfMemoryError e) {
                VolleyLog.e("Caught OOM for %d byte image, url=%s", response.data.length, getUrl());
                return Response.error(new ParseError(e));
            }
        }
    }

    /**
     * The real guts of parseNetworkResponse. Broken out for readability.
     */
    private Response doParse(NetworkResponse response) {
        byte[] data = response.data;
        BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
        Bitmap bitmap = null;
        if (mMaxWidth == 0 && mMaxHeight == 0) {
            decodeOptions.inPreferredConfig = mDecodeConfig;
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
        } else {
            // If we have to resize this image, first get the natural bounds.
            decodeOptions.inJustDecodeBounds = true;
            BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
            int actualWidth = decodeOptions.outWidth;
            int actualHeight = decodeOptions.outHeight;

            // Then compute the dimensions we would ideally like to decode to.
            int desiredWidth = getResizedDimension(mMaxWidth, mMaxHeight,
                    actualWidth, actualHeight, mScaleType);
            int desiredHeight = getResizedDimension(mMaxHeight, mMaxWidth,
                    actualHeight, actualWidth, mScaleType);

            // Decode to the nearest power of two scaling factor.
            decodeOptions.inJustDecodeBounds = false;
            // TODO(ficus): Do we need this or is it okay since API 8 doesn't support it?
            // decodeOptions.inPreferQualityOverSpeed = PREFER_QUALITY_OVER_SPEED;
            decodeOptions.inSampleSize =
                findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight);
            Bitmap tempBitmap =
                BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);

            // If necessary, scale down to the maximal acceptable size.
            if (tempBitmap != null && (tempBitmap.getWidth() > desiredWidth ||
                    tempBitmap.getHeight() > desiredHeight)) {
                bitmap = Bitmap.createScaledBitmap(tempBitmap,
                        desiredWidth, desiredHeight, true);
                tempBitmap.recycle();
            } else {
                bitmap = tempBitmap;
            }
        }

        if (bitmap == null) {
            return Response.error(new ParseError(response));
        } else {
            return Response.success(bitmap, HttpHeaderParser.parseCacheHeaders(response));
        }
    }

doParse中對圖片進行了縮放處理,可以看到當mMaxWidth == 0 && mMaxHeight == 0時,沒有做過多的處理,這種情況適合於不打的圖片,否則容易導致內存溢出。else中對圖片進行了縮放處理,首先創建一個Options 對象,並設置decodeOptions.inJustDecodeBounds = true,然後使用BitmapFactory.decodeFile(pathName, decodeOptions);時就可以只獲取圖片的大小,而不需要把圖片完全讀到內存中,
BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);可以直接從內存中獲取圖片的寬高,之後就可以使用
int actualWidth = decodeOptions.outWidth;
int actualHeight = decodeOptions.outHeight;
來獲取圖片寬高了。

獲取到圖片寬高後需要通過findBestSampleSize找到一個合適的縮放比例並賦值給decodeOptions.inSampleSize,縮放比例一定是2的n次冪。即使不是2的冪最終也會按2的n次冪處理

 static int findBestSampleSize(
            int actualWidth, int actualHeight, int desiredWidth, int desiredHeight) {
        double wr = (double) actualWidth / desiredWidth;
        double hr = (double) actualHeight / desiredHeight;
        double ratio = Math.min(wr, hr);
        float n = 1.0f;
        while ((n * 2) <= ratio) {
            n *= 2;
        }

        return (int) n;
    }

java
/**
* If set to a value > 1, requests the decoder to subsample the original
* image, returning a smaller image to save memory. The sample size is
* the number of pixels in either dimension that correspond to a single
* pixel in the decoded bitmap. For example, inSampleSize == 4 returns
* an image that is 1/4 the width/height of the original, and 1/16 the
* number of pixels. Any value <= 1 is treated the same as 1. Note: the
* decoder uses a final value based on powers of 2, any other value will
* be rounded down to the nearest power of 2.
*/
public int inSampleSize;

獲取到縮放比例後就可以通過一下代碼獲取到圖片了

“`java
decodeOptions.inJustDecodeBounds = false;
decodeOptions.inSampleSize =
findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight);
Bitmap tempBitmap =BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);

“`

Handler

Volley進行網絡請求是在非ui線程中進行的,回調是怎麼跑到ui線程中執行的呢?
Volley在創建RequestQueue時new 了一個 ExecutorDelivery(new Handler(Looper.getMainLooper()))

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

以前使用handler時我們都是直接new Handler(),沒有跟任何參數,但不跟參數的Handler默認使用的是該線程獨有的Looper,默認情況下ui線程是有Looper的而其他線程是沒有Looper的,在非UI線程中直接new Handler()會出錯,我們可以通過Looper.getMainLooper()得到ui線程的Looper,這樣任何線程都可以使用ui線程的Looper了,而且可以在任何線程中創建Handler,並且使用handler發送消息時就會跑到ui線程執行了。

也就是說如果我們想在任何線程中都可以創建Hadler,並且handler發送的消息要在ui線程執行的話,就可以采用這種方式創建Handler

new Handler(Looper.getMainLooper());

volley gson改造

在實際開發中我們會遇到對文字表情的混排處理,一種做法是服務端直接返回轉意後的字符串(比如 ? 用 \:wx 代替),然後客戶端每次都要在ui線程中解析字符串轉換成Spanned,若是在ListView中,滾動就會非常卡頓。

我們可以自定義一個XJsonRequest並繼承自Request,同時為XJsonRequest增加一個注冊gson類型轉換的方法,並把泛型參數中圖文混排字段設置為Spanned,然後在Response parseNetworkResponse(NetworkResponse response)中把圖文混拍json轉換成Spanned即可,由於Response parseNetworkResponse(NetworkResponse response)是在非ui線程中執行的,所已不會導致ANR。

volley okhttp改造



public class OkHttpStack implements HttpStack {
    private final OkHttpClient mClient;

    public OkHttpStack(OkHttpClient client) {
        this.mClient = client;
    }

    @Override
    public HttpResponse performRequest(com.android.volley.Request request, Map additionalHeaders)
            throws IOException, AuthFailureError {
        OkHttpClient client = mClient.clone();
        int timeoutMs = request.getTimeoutMs();
        client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
        client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
        client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

        com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder();
        okHttpRequestBuilder.url(request.getUrl());

        Map headers = request.getHeaders();

        for (final String name : headers.keySet()) {
            if (name!=null&& headers.get(name)!=null) {
                okHttpRequestBuilder.addHeader(name, headers.get(name));
            }

        }

        for (final String name : additionalHeaders.keySet()) {
            if (name!=null&& headers.get(name)!=null) 
                okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
        }

        setConnectionParametersForRequest(okHttpRequestBuilder, request);

        com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
        Response okHttpResponse = client.newCall(okHttpRequest).execute();

        StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(),
                okHttpResponse.message());

        BasicHttpResponse response = new BasicHttpResponse(responseStatus);
        response.setEntity(entityFromOkHttpResponse(okHttpResponse));

        Headers responseHeaders = okHttpResponse.headers();

        for (int i = 0, len = responseHeaders.size(); i < len; i++) {
            final String name = responseHeaders.name(i), value = responseHeaders.value(i);

            if (name != null) {
                response.addHeader(new BasicHeader(name, value));
            }
        }

        return response;
    }

    private static HttpEntity entityFromOkHttpResponse(Response r) throws IOException {
        BasicHttpEntity entity = new BasicHttpEntity();
        ResponseBody body = r.body();

        entity.setContent(body.byteStream());
        entity.setContentLength(body.contentLength());
        entity.setContentEncoding(r.header("Content-Encoding"));

        if (body.contentType() != null) {
            entity.setContentType(body.contentType().type());
        }
        return entity;
    }


    private static void setConnectionParametersForRequest(com.squareup.okhttp.Request.Builder builder,
            com.android.volley.Request request) throws IOException, AuthFailureError {
        switch (request.getMethod()) {
        case com.android.volley.Request.Method.DEPRECATED_GET_OR_POST:
            // Ensure backwards compatibility.
            // Volley assumes a request with a null body is a GET.
            byte[] postBody = request.getPostBody();

            if (postBody != null) {
                builder.post(RequestBody.create(MediaType.parse(request.getPostBodyContentType()), postBody));
            }
            break;

        case com.android.volley.Request.Method.GET:
            builder.get();
            break;

        case com.android.volley.Request.Method.DELETE:
            builder.delete();
            break;

        case com.android.volley.Request.Method.POST:
            builder.post(createRequestBody(request));
            break;

        case com.android.volley.Request.Method.PUT:
            builder.put(createRequestBody(request));
            break;

        // case com.android.volley.Request.Method.HEAD:
        // builder.head();
        // break;
        //
        // case com.android.volley.Request.Method.OPTIONS:
        // builder.method("OPTIONS", null);
        // break;
        //
        // case com.android.volley.Request.Method.TRACE:
        // builder.method("TRACE", null);
        // break;
        //
        // case com.android.volley.Request.Method.PATCH:
        // builder.patch(createRequestBody(request));
        // break;

        default:
            throw new IllegalStateException("Unknown method type.");
        }
    }

    private static ProtocolVersion parseProtocol(final Protocol p) {
        switch (p) {
        case HTTP_1_0:
            return new ProtocolVersion("HTTP", 1, 0);
        case HTTP_1_1:
            return new ProtocolVersion("HTTP", 1, 1);
        case SPDY_3:
            return new ProtocolVersion("SPDY", 3, 1);
        case HTTP_2:
            return new ProtocolVersion("HTTP", 2, 0);
        }

        throw new IllegalAccessError("Unkwown protocol");
    }

    private static RequestBody createRequestBody(com.android.volley.Request r) throws AuthFailureError {
        final byte[] body = r.getBody();
        if (body == null)
            return null;

        return RequestBody.create(MediaType.parse(r.getBodyContentType()), body);
    }
}

END

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