繁体   English   中英

Android Volley:在何处添加重试策略和超时?

[英]Android Volley: where add retry policy and timeout?

请,我不知道添加/编辑超时和重试策略的位置。 基本上我需要3秒钟。 超时,并且资源策略设置为零。

我正在使用网上找到的图案。

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 <T> void addToRequestQueue(Request<T> 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 <T> void addToRequestQueue(Request<T> 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<JSONObject> {

    private Response.Listener<JSONObject> listener;
    private Map<String, String> params;

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

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

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

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

    @Override
    protected Response<JSONObject> 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<String> callback, String username, String password) {

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

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

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

    }

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

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

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

这个堆栈溢出问题将为您提供帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM