android - 将 Volley 与 Sync Adapter 结合使用

标签 android multithreading android-volley android-syncadapter

我对此进行了很多搜索,但找不到任何解决方案。很长一段时间以来,我一直在使用 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
}

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

关于android - 将 Volley 与 Sync Adapter 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35824502/

相关文章:

c# - 为什么方法调用会将非 volatile 变量的值刷新到主线程?

android - GPS 应用程序中的风向和风速

安卓支持库 v4 :22+ crashing pre Lollipop on attr/in drawables

c - pthread_cond_broadcast 的意外行为

android-volley - Volley 重试请求

java - Android Volley 错误 : com. android.volley.ClientError

Android https请求,ssl协议(protocol)失败

android - FFMPEG : Adding font to Video gives error

java - 在 Android Studio 中膨胀类 EditText 时出错

c++ - 线程数组并试图将多个参数传递给函数不起作用?