【问题标题】:Android Volley multiple RequestsAndroid Volley 多个请求
【发布时间】:2015-06-17 13:57:03
【问题描述】:

我尝试在当前的 volley 请求中执行一个新的 volley 请求,但是当新的请求被调用时,它并没有进入 onrespond 方法。

新请求应在第一个结束之前执行。 (后进先出)

我怎样才能成功执行新的请求?

private void makeJsonObjectRequest() {
    ac = new AppController();


    final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
            url, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            Log.d("test", response.toString());

            try {
                // Parsing json object response
                // response will be a json object


                JSONArray name = response.getJSONArray("data");
                for (int i = 0; i < name.length(); i++) {
                    JSONObject post = (JSONObject) name.getJSONObject(i);

                    try {
                        objectid = post.getString("object_id");

                        newRequest(objectid);

                    }
                    catch (Exception e) {

                   }

                }


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

            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d("test", "Error: " + error.getMessage());
        }
    });

    // Adding request to request queue
    ac.getInstance().addToRequestQueue(jsonObjReq);
}

【问题讨论】:

  • 将 Priority.HIGH 设置为内部请求,将 Priority.LOW 设置为外部请求

标签: android json android-volley


【解决方案1】:

100% 试用

public class Utility {
String result = "";

String tag_string_req = "string_raq";
private Activity activity;
Context context;
private LinearLayout mLinear;
private ProgressDialog pDialog;
public Utility(Context context) {
    this.context = context;
}

public String getString(String url, final VolleyCallback callback) {
    showpDialog();
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            result = response;
            hideDialog();
            callback.onSuccess(response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            callback.onRequestError(error);
            hideDialog();
           /*LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            View layout = inflater.inflate(R.layout.custom_toast, null);
            ((Activity) context).setContentView(layout);*/

        }
    });
    VolleySingleton.getInstance().addToRequestQueue(stringRequest, tag_string_req);
    stringRequest.setRetryPolicy(
            new DefaultRetryPolicy(1 * 1000, 1, 1.0f));
    return result;
}

public interface VolleyCallback {
    void onSuccess(String result);
    void onRequestError(VolleyError errorMessage);
    //void onJsonInvoke(String url, final VolleyCallback callback);
}

public boolean isOnline() {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int exitValue = ipProcess.waitFor();
        return (exitValue == 0);

    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    return false;
}

private void showpDialog() {
    onProgress();
    if (!pDialog.isShowing())
        pDialog.show();
}

private void hideDialog() {
    if (pDialog.isShowing())
        pDialog.dismiss();
}

public void onProgress() {
    pDialog = new ProgressDialog(context);
    pDialog.setMessage("Please wait...");
    pDialog.setCancelable(false);
    pDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
}

}

调用片段

Utility utility = new Utility(getContext());
    utility.getString(urls, new Utility.VolleyCallback() {
        @Override
        public void onSuccess(String result) {
            try {
                JSONObject toplinks = new JSONObject(result);
                JSONObject data  = toplinks.getJSONObject("toplinks");
                M.i("============LS", "" + data);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            finally {

            }
        }
        @Override
        public void onRequestError(VolleyError errorMessage) {
            errorJson.setVisibility(View.VISIBLE);
            String msg = VolleyException.getErrorMessageFromVolleyError(errorMessage);
            errorJson.setText(msg);
        }
    });

【讨论】:

  • 一个请求看起来不错。就我而言,我有 5 个请求要执行,但第一个请求必须在接下来的 4 个请求之前完成。接下来的 4 个请求可以并行进行。有什么建议,我该如何实现?
【解决方案2】:

这一切都是关于

请求优先级

网络调用是实时操作,因此请考虑我们有多个请求,例如您的情况,Volley 按照先进先出的顺序处理从较高优先级到较低优先级的请求。

因此,您只需更改优先级(设置Priority.HIGH)以请求您首先处理。

这是一段代码

public class CustomPriorityRequest extends JsonObjectRequest {

// default value
    Priority mPriority = Priority.HIGH;

    public CustomPriorityRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
        super(method, url, jsonRequest, listener, errorListener);
    }

    public CustomPriorityRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
        super(url, jsonRequest, listener, errorListener);
    }

    @Override
    public Priority getPriority() {
        return mPriority;
    }

    public void setPriority(Priority p){
        mPriority = p;
    }
}

【讨论】:

    【解决方案3】:

    正如其他人所提到的,一种方法是将请求置于高优先级。

    另一个选项,因为您似乎有第一个请求,具体取决于包装在 try-catch 块中的内部请求,在我看来,您希望针对这种特定情况实现同步/阻塞行为。那么你可以使用RequestFuture:

    RequestFuture<String> future = RequestFuture.newFuture();
    StringRequest request = newRequest(objectid, future);
    requestQueue.add(request);
    String result = future.get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-08
      • 2015-05-17
      • 2016-09-19
      相关资源
      最近更新 更多