Android: Cancel Volley request during execution due to slow connection

邮差的信 提交于 2019-12-12 10:16:52

问题


I'm using Volley in Android in order to make requests including fetching relatively large amount of data. I want to make timer of 5 seconds and if after it the request not returned - it probably means that there is slow connection and therefore I want to cancel the request. So far what I did:

Timer timer = new Timer();
VioozerVolleyRequestFactory mFactory = new VioozerVolleyRequestFactory(this);
RequestQueue mQueue = VioozerVolleySingleton.getInstance(this).getRequestQueue();
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        mQueue.cancelAll("MY_TAG");
    }
}, 5000};
Request<String> request = mFactory.createRequest(RequestType, 
    new Listener<String>() {
        @Override
        public void onResponse(String response) {
           timer.cancel();
           //...
        }
    },
    new ErrorListener<String>() {
        @Override
        public void onErrorResponse(String response) {
          timer.cancel(); 
          //...
        }
    }, extra);
request.setTag("MY_TAG");
mQueue.add(request);

My question: It seems that the request not canceled. The request is executed so the build in method cancelALL(TAG) not relevant here. How can I still achieve my requirement?

Thanks,


回答1:


By default Volley request timeout is set to 2500ms and it makes 1 retry per request.

You need to override DefaultRetryPolicy of Request.

for example:

Wait for 5000ms and do not perform any retry.

request.setRetryPolicy(new DefaultRetryPolicy(5000,0,1f));

Ref: DefaultRetryPolicy.java



来源:https://stackoverflow.com/questions/32763067/android-cancel-volley-request-during-execution-due-to-slow-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!