4

我已经搜索了很多关于此,但无法找到任何解决方案。很长一段时间我一直在使用Volley来处理我的网络通信。最近我决定使用SyncAdapter将我的数据同步到服务器。在onPerformSync()方法中,我想我将使用Volley将数据发送到服务器,因为使用Volley很容易进行GET,POST请求。使用同步适配器排球

问题 - SyncAdapter和Volley都使用他们自己的单独线程。因此,当我从onPerformSync()方法中启动Volley请求时,SyncAdapter不会等待Volley请求完成并在收到Volley的onResponse()onErrorResponse()回调之前完成同步。在第一次通话成功返回后,我需要在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等到网络响应由排球收到?

回答

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?