适用范围
由于数据解析和暂存,都是存储在内存中,所以不适合下载大件。
请求流程
- 创建请求队列
- 构建HTTP请求
- 添加请求到队列
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算法达到缓存byte[] 目的,减少GC开销
public class ByteArrayPool {
/** 这是一个按照时间排序的回收队列,便于回收 */
private final List<byte[]> mBuffersByLastUse = new ArrayList<>();
/** 这是一个按照内存块大小排序的回收队列,便于查找 */
private final List<byte[]> mBuffersBySize = new ArrayList<>(64);
/** 内存池当前大小*/
private int mCurrentSize = 0;
/** 最大尺寸限制 */
private final int mSizeLimit;
/** 根据内存尺寸进行排列 */
protected static final Comparator<byte[]> BUF_COMPARATOR =
new Comparator<byte[]>() {
@Override
public int compare(byte[] lhs, byte[] rhs) {
return lhs.length - rhs.length;
}
};
/** 通过设置大小,来创建内存池 */
public ByteArrayPool(int sizeLimit) {
mSizeLimit = sizeLimit;
}
/**
获取一块内存
*/
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];
}
/**
回收一块内存
*/
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();
}
/** 移除内存块,直到达到尺寸要求 */
private synchronized void trim() {
while (mCurrentSize > mSizeLimit) {
byte[] buf = mBuffersByLastUse.remove(0);
mBuffersBySize.remove(buf);
mCurrentSize -= buf.length;
}
}
}