首页 > 解决方案 > 在 CancelAll 之后删除队列中剩余的请求

问题描述

下面的代码中,在CancelAll和Stop之后,后面添加到队列中的请求,会在start命令之后立即执行。

如何删除插入队列中的最后一个请求/请求?

    final  RequestQueue queue = Volley.newRequestQueue(this);
    String url ="";

    // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    Log.d("response", response);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("VolleyError", error.toString());
        }
    });

    // Add the request to the RequestQueue.

    stringRequest.setTag("a");
    queue.cancelAll("a");
    queue.stop();
    queue.add(stringRequest);
    queue.start();

标签: javaandroidandroid-volley

解决方案


由于您queue引用的是一个局部变量,因此您需要将其移到外部,并且由于您在活动中使用它,因此将其声明为

private RequestQueue queue;

..oncreate(..){
    //... code
    queue = Volley.newRequestQueue(this);
}

并创建一个单独的方法来取消所有请求

void cancelAllQueuedRequests(){
    queue.cancelAll("a");
    queue.stop();
    queue.start();
}

cancelAllQueuedRequests随时随地拨打电话并添加这样的请求

String url ="some url";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                Log.d("response", response);
            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.d("VolleyError", error.toString());
        cancelAllQueuedRequests();
    }
});

// Add the request to the RequestQueue.

stringRequest.setTag("a");
queue.add(stringRequest);
//queue.start(); no need

推荐阅读