gpt4 book ai didi

android - Volley - 串行请求而不是并行?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:55:30 26 4
gpt4 key购买 nike

我正在使用 volley 从我的 Android 应用程序发出 HTTP 请求。这是我正在使用的代码:

public class RequestPool {


private static RequestPool mInstance;

private RequestQueue mRequestQueue;

private static Context mContext;

private RequestPool(Context context) {

mContext = context;
mRequestQueue = getRequestQueue();


}

public static synchronized RequestPool getInstance(Context context) {

if (mInstance == null) {
mInstance = new RequestPool(context);
}
return mInstance;
}

public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
}

return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req) {

getRequestQueue().add(req);
}
}

我想将请求添加到队列中但控制它们的执行方式,例如:

在任意时间向池中添加多个请求,池将只执行第一个请求(队列的头部),然后在完成时执行下一个......等等......

也许有一种方法可以同时执行串行和并行请求?

这可能吗?

谢谢。

最佳答案

这可以通过创建线程池为 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);
}

在 getNetwork() 方法中

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

然后我们使用 start() 方法来启动请求队列。

RequestQueue serialRequestQueue = prepareSerialRequestQueue(context);
serialRequestQueue.start();

现在将请求添加到此队列而不是 volleys 请求队列。例如:

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

在这种情况下,将首先处理结果 requestTwo,然后分别处理 requestOnerequestThree。如果您不想阻止请求处理并让它们连续发生,这会有所帮助。

关于android - Volley - 串行请求而不是并行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30149453/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com