使用Volley和同步适配器

时间:2016-03-06 07:59:47

标签: android multithreading android-volley android-syncadapter

我搜索了很多关于此的内容,但找不到任何解决方案。我一直在使用 Volley 来处理我的网络通信。最近我决定使用SyncAdapter将我的数据同步到服务器。在onPerformSync()方法中,我认为我将使用Volley将数据发送到服务器,因为Volley很容易发出GET,POST请求。

问题 - SyncAdapter和Volley都使用自己独立的线程。因此,当我从onPerformSync()方法内部发起排球请求时,SyncAdapter不会等待排球请求完成,并在onResponse()onErrorResponse()回调之前完成同步收到了Volley。在第一次调用成功返回后,我需要在SyncAdapter内进行进一步的网络调用。

示例代码 -

@Override
    public void onPerformSync(Account account, Bundle extras, String authority,
                              ContentProviderClient provider, SyncResult syncResult) {

        JsonObjectRequest jReq = new JsonObjectRequest(Method.POST, url, data,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.i(TAG, "response = " + response.toString());
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(TAG, "error = " + error.getMessage());
                }
            });

        AppController.getInstance().addToRequestQueue(jReq);  

    //onPerformSync() exits before request finished   
    }

问题 - 那么如何让SyncAdapter等到Volley收到网络响应?

1 个答案:

答案 0 :(得分:3)

制作同步截击请求。

RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(URL, null, future, future);
requestQueue.add(request);

然后使用:

try {
  JSONObject response = future.get(); // this will block (forever)
} catch (InterruptedException e) {
  // exception handling
} catch (ExecutionException e) {
  // exception handling
}

代码来自:Can I do a synchronous request with volley?