編輯:關於 Android 程式設計
Volley 這個名字原意是「齊射」,2013 年的 Google I/O 大會上發布,是 Android 平台的網路通訊庫。它把 AsyncHttpClient 的易用與 Universal-Image-Loader 的圖片加載能力揉在一起,既能簡潔地做 HTTP 通信,也能輕鬆載入網路圖片。
它的設計目標非常明確:資料量不大、但通信頻繁的場景。演講配圖是一排發射中的弓箭,隱喻正是如此。反過來說,下載大檔案這類任務,Volley 的表現會很糟——因為所有回應都會先被完整讀進記憶體。


使用 Volley 的第一步永遠是取得 RequestQueue:
RequestQueue queue = Volley.newRequestQueue(context);
這個方法最終會走到帶 HttpStack 參數的重載版本,關鍵步驟有四個:
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 {
// Gingerbread 之前 HttpURLConnection 不太可靠
stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
}
}
Network network = new BasicNetwork(stack);
RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
queue.start();
return queue;
}
HttpStack 是一個介面,只負責發請求並回傳結果,預設依系統版本在 HurlStack 與 HttpClientStack 之間選擇。想換成 OkHttp,只要實作這個介面即可:
HttpResponse performRequest(Request request, Map<String, String> additionalHeaders)
throws IOException, AuthFailureError;
把 OkHttp 的結果包裝成 HttpResponse 返回,裡面包含狀態碼、響應頭與 body 即可。
BasicNetwork 使用 HttpStack 執行請求,成功後回傳 NetworkResponse——一個只記錄狀態碼、body、響應頭、是否為 304 以及耗時的輕量物件。
RequestQueue 內部持有一個 DiskBasedCache,預設容量 5MB。快取檔是二進位格式,開頭寫了一個特殊整數「魔數」用於自我識別。初始化時會掃描目錄下所有檔案,魔數不符的直接刪除,符合的則把檔頭資訊讀進記憶體:
public synchronized void initialize() {
File[] files = mRootDirectory.listFiles();
if (files == null) {
return;
}
for (File file : files) {
try (BufferedInputStream fis =
new BufferedInputStream(new FileInputStream(file))) {
CacheHeader entry = CacheHeader.readHeader(fis);
entry.size = file.length();
putEntry(entry.key, entry);
} catch (IOException e) {
file.delete();
}
}
}
除了 int、long,快取檔也能存 String 與 Map,都是靠固定位元組數的 readLong 逐位元組組裝:
static long readLong(InputStream is) throws IOException {
long n = 0;
n |= ((read(is) & 0xFFL) << 0);
n |= ((read(is) & 0xFFL) << 8);
// ... 依此類推到 56
return n;
}
快取檔名由 cache key 前半段的 hashCode 拼上後半段的 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;
}
空間不足時的淘汰策略相當樸素——直接遍歷 mEntries 刪到小於上限的九成,並不做 LRU 排序:
private void pruneIfNeeded(int neededSpace) {
if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes) {
return;
}
Iterator<Map.Entry<String, CacheHeader>> it = mEntries.entrySet().iterator();
while (it.hasNext()) {
CacheHeader e = it.next().getValue();
if (getFileForKey(e.key).delete()) {
mTotalSize -= e.size;
}
it.remove();
if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes * 0.9f) {
break;
}
}
}
RequestQueue 只是一個普通類,它的 start() 會建立一個 CacheDispatcher 與四個(可配置)NetworkDispatcher。這五個都是 Thread 的直接子類,也就是前面說的「搶請求」的執行緒。
public void start() {
stop(); // 先確保舊線程全部退出
mCacheDispatcher = new CacheDispatcher(
mCacheQueue, mNetworkQueue, mCache, mDelivery);
mCacheDispatcher.start();
for (int i = 0; i < mDispatchers.length; i++) {
NetworkDispatcher dispatcher =
new NetworkDispatcher(mNetworkQueue, mNetwork, mCache, mDelivery);
mDispatchers[i] = dispatcher;
dispatcher.start();
}
mCache.initialize(); // 讀檔較耗時,放在子線程做
}
stop() 則是對每個線程呼叫 quit(),把 mQuit 設為 true 並 interrupt,讓 run 迴圈退出。
兩個 Dispatcher 的 run 方法結構幾乎一樣,都是在 while (true) 裡對 PriorityBlockingQueue 呼叫 take()。這是個阻塞佇列,空的时候会卡住直到有請求進來,本身也是線程安全的,因此同一個請求只會被五個線程中的一個取走,並可依照優先級排序。
Volley 預設提供 ImageRequest、JsonObjectRequest、JsonArrayRequest、StringRequest 四種,使用方式統一是「new 出來丟進佇列」:
Request<String> request = new StringRequest(
Method.GET, "https://mogujie.com",
new Response.Listener<String>() {
@Override public void onResponse(String response) { }
},
new Response.ErrorListener() {
@Override public void onErrorResponse(VolleyError error) { }
});
Volley.newRequestQueue(context).add(request);
add 方法做了幾件事:綁定所屬佇列(方便日後取消時移除)、依加入順序編號(同一佇列內序號唯一,會影響同優先級間的排序)、打 debug 標記,最後分兩路:
request.shouldCache() 為 false,直接丟進 mNetworkQueue,讓四個 NetworkDispatcher 去搶;是否緩存由 Request 的成員決定,預設是開的:
private boolean mShouldCache = true;
這個「請求合併」機制是 Volley 值得學的一點:ListView 快速滾動時大量重複 URL 不會打爆後端。
它取到請求後先確認是否已被取消,是則直接 finish;接著查快取:
if (request.isCanceled()) {
request.finish("cache-discard-canceled");
continue;
}
Cache.Entry entry = mCache.get(request.getCacheKey());
if (entry == null) {
mNetworkQueue.put(request); // 完全未命中
continue;
}
if (entry.isExpired()) {
request.setCacheEntry(entry);
mNetworkQueue.put(request); // 過期,帶著舊資料去網路驗證
continue;
}
命中且未過期時,用快取資料組出 NetworkResponse 交給 request.parseNetworkResponse 解析,再把結果丟回 UI 執行緒回呼 listener,然後 finish 自己;若還需要刷新,則同樣轉給 NetworkDispatcher。
NetworkDispatcher 拿到新資料後會順手更新快取:
if (request.shouldCache() && response.cacheEntry != null) {
mCache.put(request.getCacheKey(), response.cacheEntry);
}
看似職責重疊,其實是為了處理 304 通知—只有網路層知道伺服器回不回 304,所以快取中介資料的更新只能放在這裡。
Request#finish 會回呼 RequestQueue#finish,把之前掛在 mWaitingRequests 裡的同 key 請求整批搬進 mCacheQueue。由於前一份請求已經把快取寫好了,這些請求再走一輪 CacheDispatcher 時就能直接命中,不必重複發網路請求。
if (request.shouldCache()) {
synchronized (mWaitingRequests) {
Queue<Request<?>> waiting = mWaitingRequests.remove(cacheKey);
if (waiting != null) {
mCacheQueue.addAll(waiting);
}
}
}
HttpHeaderParser.parseCacheHeaders 負責把原始字串切成響應頭,再把響應頭與 body 一起打包成 Cache.Entry 回傳,後續的過期判斷都靠這裡解析出的資訊。
Volley 把重試策略放在 Request 上,因此每個請求都能有自己的一套規則。Request 建構時預設帶入 DefaultRetryPolicy:
public Request(int method, String url, Response.ErrorListener listener) {
mMethod = method;
mUrl = url;
mErrorListener = listener;
setRetryPolicy(new DefaultRetryPolicy());
mDefaultTrafficStatsTag = findDefaultTrafficStatsTag(url);
}
RetryPolicy 介面只暴露三個方法:當前超時時間、當前重試次數,以及 retry(error)。DefaultRetryPolicy 的實作是「加退避」:
public void retry(VolleyError error) throws VolleyError {
mCurrentRetryCount++;
mCurrentTimeoutMs += (mCurrentTimeoutMs * mBackoffMultiplier);
if (!hasAttemptRemaining()) {
throw error;
}
}
BasicNetwork 在 performRequest 的 while 迴圈中攔截 SocketTimeoutException、ConnectTimeoutException 等異常,交給 attemptRetryOnException 判斷是否再來一次;超過上限就把 VolleyError 往上拋,迴圈終止。
ByteArrayOutputStream 內部有兩個 protected 成員:buf 暫存資料,count 記錄已用大小。它原本的 expand 在空間不足時直接 new 一個兩倍大的陣列,舊陣列等 GC 回收:
private void expand(int i) {
if (count + i <= buf.length) {
return;
}
byte[] newbuf = new byte[(count + i) * 2];
System.arraycopy(buf, 0, newbuf, 0, count);
buf = newbuf;
}
PoolingByteArrayOutputStream 繼承它並重寫 expand,改成從 ByteArrayPool 借一塊夠大的陣列,並把舊的還回去:
private void expand(int i) {
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;
}
它的建構方法直接把 buf 設為從池裡借來的陣列,所以後續 write 都寫在池的記憶體上。getBuf 會線性掃過 mBuffersBySize 找一塊夠大的,找到就從兩個 List 中移除並回傳,否則才 new:
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 與 returnBuf 都加了 synchronized。returnBuf 會依大小二分插入 mBuffersBySize,並用 mBuffersByLastUse 記錄歸還順序,超標時由 trim() 從最舊的開始丟棄。BasicNetwork 在 entityToBytes 中用完後會 returnBuf 並 close 掉串流,形成完整的借還閉環。
ImageRequest request = new ImageRequest(
url,
new Response.Listener<Bitmap>() {
@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);
}
});
六個參數分別是:圖片 URL、成功回呼、最大寬、最大高、色彩配置、失敗回呼。寬高填 0 表示不壓縮;色彩配置中 ARGB_8888 每像素 4 位元組、還原度最好,RGB_565 每像素 2 位元組、省一半記憶體。預設使用 GET,並以 ScaleType.CENTER_INSIDE 縮放。
doParse 的縮放策略值得細看:
if (mMaxWidth == 0 && mMaxHeight == 0) {
decodeOptions.inPreferredConfig = mDecodeConfig;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
} else {
decodeOptions.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
int actualWidth = decodeOptions.outWidth;
int actualHeight = decodeOptions.outHeight;
int desiredWidth = getResizedDimension(mMaxWidth, mMaxHeight,
actualWidth, actualHeight, mScaleType);
int desiredHeight = getResizedDimension(mMaxHeight, mMaxWidth,
actualHeight, actualWidth, mScaleType);
decodeOptions.inJustDecodeBounds = false;
decodeOptions.inSampleSize = findBestSampleSize(
actualWidth, actualHeight, desiredWidth, desiredHeight);
Bitmap temp = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
if (temp != null && (temp.getWidth() > desiredWidth
|| temp.getHeight() > desiredHeight)) {
bitmap = Bitmap.createScaledBitmap(temp, desiredWidth, desiredHeight, true);
temp.recycle();
} else {
bitmap = temp;
}
}
也就是兩段式:先只讀邊界取得原始尺寸,算出 2 的 n 次冪 inSampleSize 做粗調,必要時再用 createScaledBitmap 做精調並回收中間圖。findBestSampleSize 的實作就是不断把 n 乘 2 直到接近目標比例:
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;
}
另外 doParse 整體包在 sDecodeLock 同步塊中,並捕捉 OutOfMemoryError 轉為 ParseError——這是刻意用解碼併發度換取峰值記憶體的做法。
答案在 RequestQueue 的建構:預設傳入 new ExecutorDelivery(new Handler(Looper.getMainLooper()))。
不帶參數的 new Handler() 綁的是當前線程的 Looper,而只有主線程才有 Looper,所以在子線程直接 new 會出錯。指定 Looper.getMainLooper() 之後,任何線程建立的 Handler 都能把訊息投到主線程執行——這是把結果送回 UI 的通用寫法。
實務上常遇到文字與表情混排。若伺服器回傳轉義後的字串,客戶端每次都要在主線程把字串解析成 Spanned,在 ListView 滾動時必然卡頓。做法是自訂一個 XJsonRequest 繼承 Request,註冊 Gson 的型別轉換,把混排欄位直接對應成 Spanned,並在 parseNetworkResponse 中完成轉換——由於這個方法跑在非 UI 線程,不會造成 ANR。
只要實作 HttpStack,在 performRequest 中把 Volley 的 Request 翻譯成 OkHttp 的請求即可,重點包括:把 getTimeoutMs 套到 connect/read/write 三種超時、複製 headers、依 Method 分派 get/post/put/delete,最後把 Response 的 body 與 headers 包裝回 Apache 風格的 HttpResponse。
public class OkHttpStack implements HttpStack {
private final OkHttpClient mClient;
@Override
public HttpResponse performRequest(com.android.volley.Request request,
Map<String, String> 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);
// 組裝 Request.Builder、執行、再轉成 HttpResponse
...
}
}
把這條鏈路串起來看:add 入隊 → CacheDispatcher 查快取 → NetworkDispatcher 搶請求 → HttpStack 發網路請求 → ByteArrayPool 複用緩衝 → parseNetworkResponse 解析 → ExecutorDelivery 丟回主線程 → listener 回呼 → finish 喚醒等待中的同類請求。理解這八步,Volley 的行為基本就都在掌握中了。
以 RecyclerView 打造高擴展性列表菜單
在許多 App 中,例如個人中心、發現頁、動態頁,常見到縱向排列的列表式菜單。這類畫面看似簡單,但若要在分割線、間距、群組與動畫上保持彈性,就需要更靈活的列表實作方式。常
Linux 進程等待與程式替換:wait、waitpid 與 exec 函數
在 Linux 系統中,父進程通常需要等待子進程結束,以取得其退出狀態並釋放相關資源。若未妥善處理,子進程可能成為僵屍進程,佔用進程表資訊。wait 與 waitpid
Android AssetManager 資源管理與加載機制解析
AssetManager 的角色 AssetManager 是 Android 的資源管理器,負責管理系統與應用層級的資源。系統資源通常來自 framework-res.
Android 加載對話框與異步執行同步實現方法
在 Android 中,透過子線程連接網路取得資料的同時,往往需要顯示一個加載進度對話框給使用者。這個功能需要 Thread 與 Handler 搭配完成:在 Threa