簡體   English   中英

使用Volley和同步適配器

[英]Using Volley with Sync Adapter

我已經搜索了很多關於這個,但找不到任何解決方案。 我一直在使用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等到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
}

代碼來自: 我可以用截擊做同步請求嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM