使用Volley进行Android开发时,我应该在哪里编写setRetryPolicy()方法调用 [英] Where should I write setRetryPolicy() method call when using Volley for Android development

查看:110
本文介绍了使用Volley进行Android开发时,我应该在哪里编写setRetryPolicy()方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个简单的问题,但我在实际代码中对其进行了测试,无法判断Volley的setRetryPolicy()函数的正确行为.任何人都请告诉我该陈述的正确立场.我应该在onErrorResponse()函数中还是在将请求输入队列之前编写此方法调用?

It might be a simple question but I tested it in actual code and unable to judge the correct behaviour of setRetryPolicy() function of Volley. Anyone please tell me the correct position of this statement to be written. Should I write this method call in onErrorResponse() function or before entering the request into the queue?

这是我的位图图像代码.我希望请求超时后20秒进行3次重试.请建议我编写正确的重试策略的位置,我是否根据需要设置了正确的重试策略?

Here is my code for bitmap image. I want 3 retries of 20 seconds after request timeout. Please suggest me the correct place for retry policy to be written and have I set the retry policy correct according to my need?

ImageRequest ir = new ImageRequest(url, new Response.Listener<Bitmap>() {

            @Override
            public void onResponse(Bitmap response) {
                      iv.setImageBitmap(response);

            }
        }, 0, 0, null, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                ir.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 2, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

            }
        });

mRequestQueue.add(ir);

推荐答案

在声明并初始化Request对象后,添加重试策略.在将请求添加到Volley队列之前,可以在任何位置添加策略.

Add the retry policy once you have declared and initialized the Request object. It's okay to add the policy anywhere before adding your request to the Volley queue.

ImageRequest  ir = new ImageRequest(url, new Response.Listener() {

        @Override
        public void onResponse(Bitmap response) {
            iv.setImageBitmap(response);
        }
    }, 0, 0, null, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            //Handle errors related to Volley such as networking issues, etc
        }
});

ir.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 2, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mRequestQueue.add(ir);

另一个说明:onErrorResponse()回调函数用于处理从Volley生成的错误.此时,您的请求已被调度,并出现一些网络错误.否则,您的代码将无法到达此回调函数.因此,在此函数中添加重试策略是没有意义的.

Another note: The onErrorResponse() callback function is used to handle errors generated from Volley. At this point, your request is already dispatched and got some networking error. Otherwise, your code would not reach this callback function. So, it's pointless to add the retry policy inside this function.

这篇关于使用Volley进行Android开发时,我应该在哪里编写setRetryPolicy()方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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