当前位置:  开发笔记 > 编程语言 > 正文

Android Volley:在哪里添加重试策略和超时?

如何解决《AndroidVolley:在哪里添加重试策略和超时?》经验,为你挑选了1个好方法。

请,我不知道添加/编辑超时和重试策略的位置.基本上我会有3秒.超时,并将rety策略设置为零.

我正在使用在网络上找到的模式.

Controller.java

public class Controller extends Application {

    /**
     * Log or request TAG
     */
    public static final String TAG = "VolleyPatterns";

    /**
     * Global request queue for Volley
     */
    private RequestQueue mRequestQueue;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    /**
     * @return The Volley Request queue, the queue will be created if it is null
     */
    public RequestQueue getRequestQueue() {
        // lazy initialize the request queue, the queue instance will be
        // created when it is accessed for the first time
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    /**
     * Adds the specified request to the global queue, if tag is specified
     * then it is used else Default TAG is used.
     *
     * @param req
     * @param tag
     */
    public  void addToRequestQueue(Request req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);

        VolleyLog.d("Adding request to queue: %s", req.getUrl());

        getRequestQueue().add(req);
    }

    /**
     * Adds the specified request to the global queue using the Default TAG.
     *
     * @param req
     * @param tag
     */
    public  void addToRequestQueue(Request req) {
        // set the default tag if tag is empty
        req.setTag(TAG);

        getRequestQueue().add(req);
    }

    /**
     * Cancels all pending requests by the specified TAG, it is important
     * to specify a TAG so that the pending/ongoing requests can be cancelled.
     *
     * @param tag
     */
    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }

}

BaseController.java

public class BaseController extends Controller {

    /**
     * A singleton instance of the application class for easy access in other places
     */
    private static Controller sInstance;

    private static String mToken = null;

    @Override
    public void onCreate() {
        super.onCreate();

        // initialize the singleton
        sInstance = this;
    }

    public static void setMtoken(String token){
        mToken = token;
    }

    public static String getMtoken(){
        return mToken;
    }

    /**
     * @return ApplicationController singleton instance
     */
    public static synchronized Controller getInstance() {
        return sInstance;
    }


}

CustomRequest.java

public class CustomRequest extends Request {

    private Response.Listener listener;
    private Map params;

    public CustomRequest(String url, Map params,
                         Response.Listener reponseListener, Response.ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    public CustomRequest(int method, String url, Map params,
                         Response.Listener reponseListener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    @Override
    protected Map getParams() throws com.android.volley.AuthFailureError {
        return params;
    };

    @Override
    protected void deliverResponse(JSONObject response) {
        listener.onResponse(response);
    }

    @Override
    protected Response parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

}

最后这是一个真正的API调用:

public void login(final VolleyCallback callback, String username, String password) {

        HashMap params = new HashMap();
        params.put("username", username);
        params.put("password", password);

        CustomRequest jsObjRequest = new CustomRequest(Request.Method.POST,
                API_URL_LOGIN, params,
                new Response.Listener() {

                    @Override
                    public void onResponse(JSONObject response) {

                        try {

                            JSONArray account = response.optJSONArray("account");

                            if (account!=null) {

                                account = response.getJSONArray("account");

                                JSONObject account2 = account.getJSONObject(0);
                                String token = account2.getString("token");

                                if (token!="null" && token!=null && token!="" && !token.isEmpty()) {

                                    callback.onSuccess(token);

                                } else {

                                    // token doens't set
                                    String result = "NO_TOKEN";
                                    callback.onSuccess(result);
                                }
                            } else {
                                // WRONG PASSWORD
                                String result = "WRONG_PASSWORD";
                                callback.onSuccess(result);
                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError response) {
                if(response instanceof NoConnectionError) {
                    /*
                    showDialog(LoginActivity.this,
                            LoginActivity.this.getString(R.string.title_no_internet_connection),
                            LoginActivity.this.getString(R.string.message_no_internet_connection));*/
                }
            }

        });

        // add the request object to the queue to be executed
        BaseController.getInstance().addToRequestQueue(jsObjRequest);

    }

小智.. 7

您可以在将请求添加到队列之前将重试策略设置为该请求

jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(
    3000, 
    0, 
    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

//Adding the request to queue
BaseController.getInstance().addToRequestQueue(jsObjRequest);

这个堆栈溢出问题可以帮到你.



1> 小智..:

您可以在将请求添加到队列之前将重试策略设置为该请求

jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(
    3000, 
    0, 
    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

//Adding the request to queue
BaseController.getInstance().addToRequestQueue(jsObjRequest);

这个堆栈溢出问题可以帮到你.

推荐阅读
黄晓敏3023
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有