我使用volley库实现了SyncAdapter。它正在工作,但后来我意识到Iam从onPerformSync方法调用异步(排球请求)代码。
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient contentProviderClient, SyncResult syncResult) {
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener() {
@Override
public void onResponse(JSONObject response) {
// time consuming code
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
// onPerformSync end reached before volley request processing ends
}
答案 0 :(得分:0)
您可以使用CountDownLatch
,但我读过,这不是在同步适配器中实现它对我有用的好方法
private CountDownLatch doneSignal = new CountDownLatch(1);
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient contentProviderClient, SyncResult syncResult) {
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener() {
@Override
public void onResponse(JSONObject response) {
// time consuming code
//put this line as the last line when everything is done
doneSignal.countDown();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
try {
doneSignal.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
// onPerformSync end reached before volley request processing ends
}