適用范圍
由于數(shù)據(jù)解析和暫存,都是存儲(chǔ)在內(nèi)存中,所以不適合下載大件。
請(qǐng)求流程
- 創(chuàng)建請(qǐng)求隊(duì)列
- 構(gòu)建HTTP請(qǐng)求
- 添加請(qǐng)求到隊(duì)列
image
JSON
String url = "http://my-json-feed";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
textView.setText("Response: " + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
ByteArrayPool
使用LRU算法達(dá)到緩存byte[] 目的,減少GC開銷
public class ByteArrayPool {
/** 這是一個(gè)按照時(shí)間排序的回收隊(duì)列,便于回收 */
private final List<byte[]> mBuffersByLastUse = new ArrayList<>();
/** 這是一個(gè)按照內(nèi)存塊大小排序的回收隊(duì)列,便于查找 */
private final List<byte[]> mBuffersBySize = new ArrayList<>(64);
/** 內(nèi)存池當(dāng)前大小*/
private int mCurrentSize = 0;
/** 最大尺寸限制 */
private final int mSizeLimit;
/** 根據(jù)內(nèi)存尺寸進(jìn)行排列 */
protected static final Comparator<byte[]> BUF_COMPARATOR =
new Comparator<byte[]>() {
@Override
public int compare(byte[] lhs, byte[] rhs) {
return lhs.length - rhs.length;
}
};
/** 通過(guò)設(shè)置大小,來(lái)創(chuàng)建內(nèi)存池 */
public ByteArrayPool(int sizeLimit) {
mSizeLimit = sizeLimit;
}
/**
獲取一塊內(nèi)存
*/
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];
}
/**
回收一塊內(nèi)存
*/
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();
}
/** 移除內(nèi)存塊,直到達(dá)到尺寸要求 */
private synchronized void trim() {
while (mCurrentSize > mSizeLimit) {
byte[] buf = mBuffersByLastUse.remove(0);
mBuffersBySize.remove(buf);
mCurrentSize -= buf.length;
}
}
}