This can be done by creating a request with the thread pool as 1.
int MAX_SERIAL_THREAD_POOL_SIZE = 1;
final int MAX_CACHE_SIZE = 2 * 1024 * 1024; //2 MB
private static RequestQueue prepareSerialRequestQueue(Context context) {
Cache cache = new DiskBasedCache(context.getCacheDir(), MAX_CACHE_SIZE);
Network network = getNetwork();
return new RequestQueue(cache, network, MAX_SERIAL_THREAD_POOL_SIZE);
}
in getNetwork() method
private static Network getNetwork() {
HttpStack stack;
if(Build.VERSION.SDK_INT >= 9) {
stack = new HurlStack();
} else {
String userAgent = "volley/0";
stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
}
return new BasicNetwork(stack);
}
and us the start method to start() the request queue.
RequestQueue serialRequestQueue = prepareSerialRequestQueue(context);
serialRequestQueue.start();
Now add the request to this queue intead of the volleys request queue. For example:
StringRequest requestOne = new StringRequest(Request.Method.GET, "http://www.example1.com", this, this);
StringRequest requestTwo = new StringRequest(Request.Method.GET, "http://www.example2.com", this, this);
StringRequest requestThree = new StringRequest(Request.Method.GET, "http://www.example3.com", this, this);
serialRequestQueue.add(requestTwo);
serialRequestQueue.add(requestOne);
serialRequestQueue.add(requestThree);
in this case the result requestTwo
will be handled first followed by requestOne
and requestThree
respectively. This helps if you dont want to block the request processing, and also make them happen serially.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…