在CancelAll之后删除队列中剩余的请求

时间:2018-06-24 19:49:40

标签: java android android-volley

在下面的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();

1 个答案:

答案 0 :(得分:1)

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
相关问题