Delete requests remaining in the Queue after Cance

2019-08-15 01:02发布

In the code below after the CancelAll and Stop, the request that added afterwards in the queue, will be immediately execute after the start command.

How can i remove the last request/requests that was inserted in queue?

    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条回答
Rolldiameter
2楼-- · 2019-08-15 01:35

As you queue reference is a local variable so you need to move it outside and since you are using it in activity so declare it like

private RequestQueue queue;

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

and create a separate method to cancel all requests as

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

call cancelAllQueuedRequests wherever you want and add requests like this

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
查看更多
登录 后发表回答