Android排球 - 在所有请求完成后获取回调

时间:2017-07-06 21:03:43

标签: android

我感谢你能给我的任何帮助。我有以下问题:

我有一个应用程序使用SyncAdapter定期和手动同步本地数据库与服务器数据。但是我需要在用户刚要登录应用程序时,执行手动同步,同时显示加载对话框。同步完成后,应隐藏对话框,并显示主要活动。你推荐什么?

我正在使用排球来处理HTTP请求。我有点困惑,因为请求总是以异步方式运行,因此很难知道所有请求何时完成以隐藏对话框。

代码如下:

VolleySingleton.getInstance(getContext()).addToRequestQueue(
        new JsonObjectRequest(
            Request.Method.GET,
            Constants.GET_URL,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    // This method sync the data
                    updateLocalData(response, syncResult);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    getContext().sendBroadcast(new Intent(Constants.SYNC_CORRUPTED_BY_SERVER));
                    Log.d(TAG, "Sync (makeLocalSync), Exception => " +
                            error.getLocalizedMessage());
                }
            }
        )
    );

对不起我的英语水平......

谢谢!

3 个答案:

答案 0 :(得分:4)

不幸的是,Volley的RequestQueue不提供任何接口或回调功能,以便在所有待处理请求完成时通知您。我发现在完成所有请求时通知的一种解决方法是为每个请求的响应或失败更新int和boolean类成员。重要的是您的请求可以访问这些成员,并且数字对应于更新的值,因此当此值下降到0时,您将知道所有请求都已完成。

private int numberOfRequestsToMake = NUMBER;
private boolean hasRequestFailed = false; 

然后,在创建请求时:

JsonObjectRequest req = new JsonObjectRequest(url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "successful request to " + url);
                    numberOfRequestsToMake--;

                    if(numberOfRequestsToMake == 0) {
                        if(!hasRequestFailed) {
                            //All requests finished correctly
                        } else {
                            //At least one request failed
                        }
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(TAG, "unsuccessful request to " + url);
                    numberOfRequestsToMake--;
                    hasRequestFailed = true;

                    if(numberOfRequestsToMake == 0) {
                        //The last request failed
                    }
                }
            }
    );

    MyVolleySingleton.getInstance().addToRequestQueue(req);

答案 1 :(得分:0)

我使用以下代码:

queue.addRequestFinishedListener(request -> {
        countRequests++;
        if (countRequests == 2) {
            Log.d("tag", "finished");
        }
    });

答案 2 :(得分:-1)

我已经解决了我的问题如下:

在每个&#34; n&#34;排球请求,在他们的方法 Response.Listener Respones.ErrorListener 我使用计数器标志允许我要处理广播,如下:

如果计数器的值等于请求数,则所有请求都已完成,然后,使用标志我检查是否有任何请求出现问题。

代码如下:

请求#n1:

    // Counter and flag to handle requests
    private static int iCountRequest;
    private static boolean bAnyErrors;
    // Before initiating all the requests, the variables must be restarted
    iCountRequest = 0;
    bAnyErrors = false;
    // Request # n1:
    VolleySingleton.getInstance(getContext()).addToRequestQueue(
            new JsonObjectRequest(
                    Request.Method.GET,
                    Constants.REQUEST_N1_URL,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            iCountRequest++;
                            // Response code..
                            sendBroadcastToActivity();
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            iCountRequest++;
                            bAnyErrors = true;
                            sendBroadcastToActivity();
                        }
                    }
            )
    );

sendBroadCast功能:

if (iCountRequest == Constants.NUMBER_OF_REQUEST) {
        if (!bAnyErrors) {
            getContext().sendBroadcast(new Intent(Constants
                    .SYNC_IN_ORDER_FINISHED));
        } else {
            getContext().sendBroadcast(new Intent(Constants
                    .SYNC_IN_ORDER_FINISHED_WITH_ERRORS));
        }
    }

VolleySingleton:

public final class VolleySingleton {

    private static VolleySingleton oSingleton;
    private RequestQueue oRQ;
    private static Context oContext;

    private VolleySingleton(Context context) {
        VolleySingleton.oContext = context;
        oRQ = getRequestQueue();
    }

    public static synchronized VolleySingleton getInstance(Context context) {
        if (oSingleton == null) {
            oSingleton = new VolleySingleton(context.getApplicationContext());
        }
        return oSingleton;
    }

    private RequestQueue getRequestQueue() {
        if (oRQ == null) {
            oRQ = Volley.newRequestQueue(oContext.getApplicationContext());
        }
        return oRQ;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

}

我希望它适合你。谢谢@FerDensetsu