我对此进行了很多搜索,但找不到任何解决方案。很长一段时间以来,我一直在使用 Volley 来处理我的网络通信。最近我决定使用 SyncAdapter
将我的数据同步到服务器。在 onPerformSync()
方法中,我想我将使用 Volley 将数据发送到服务器,因为使用 Volley 可以很容易地发出 GET、POST 请求。
问题 - SyncAdapter
和 Volley 都使用它们自己的独立线程。因此,当我从 onPerformSync()
方法内部发起 Volley 请求时,SyncAdapter
不会等待 Volley 请求完成并在 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 收到网络响应?
最佳答案
发出同步截击请求。
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
}
关于android - 将 Volley 与 Sync Adapter 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35824502/