Android:由于连线速度缓慢,在执行期间取消Volley请求 [英] Android: Cancel Volley request during execution due to slow connection

查看:83
本文介绍了Android:由于连线速度缓慢,在执行期间取消Volley请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Android中使用 Volley 来发出请求包括获取相对大量的数据.我想设置5秒钟的计时器,如果在此之后请求未返回,则可能意味着连接速度很慢,因此我想取消该请求.到目前为止,我做了什么:

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

我的问题:似乎请求没有取消.由于执行了请求,因此内置方法cancelALL(TAG)在这里不相关.我怎么还能达到我的要求?

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?

谢谢

推荐答案

默认情况下,Volley请求超时设置为2500ms,每个请求进行1次重试.

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

您需要覆盖请求的DefaultRetryPolicy.

You need to override DefaultRetryPolicy of Request.

例如:

等待5000毫秒,并且不执行任何重试.

Wait for 5000ms and do not perform any retry.

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

参考: DefaultRetryPolicy.java

这篇关于Android:由于连线速度缓慢,在执行期间取消Volley请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆