【问题标题】:Android: Cancel Volley request during execution due to slow connectionAndroid:由于连接速度慢,在执行期间取消 Volley 请求
【发布时间】:2015-09-26 13:27:56
【问题描述】:

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

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) 与此处无关。我怎样才能达到我的要求?

谢谢,

【问题讨论】:

    标签: android android-volley timertask


    【解决方案1】:

    默认情况下,Volley 请求超时设置为 2500 毫秒,每个请求重试 1 次。

    您需要覆盖 Request 的 DefaultRetryPolicy。

    例如:

    等待 5000 毫秒,不要执行任何重试。

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

    参考:DefaultRetryPolicy.java

    【讨论】:

    • 执行机制是什么?首先我们将它推入队列,然后它在那里等待执行。当它最终在 1 秒后执行(假设执行本身需要 2 秒)时,我想取消它,所以我发送 cancel()。会发生什么?
    • 该请求的响应到达时将被忽略。要了解更多内部工作原理:Volley: Easy, Fast Networking for Android
    • 谢谢,这让我想到了新问题:stackoverflow.com/questions/32838724/…
    猜你喜欢
    • 2015-05-17
    • 2013-07-03
    • 2013-05-22
    • 2013-01-15
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    相关资源
    最近更新 更多