我想在不同的线程中使用Volley Library进行请求.
这意味着,在Tread和UIThread中的数据过程中有一个连接.
我想这样做,因为我有很多连接,所以很多数据要处理,今天我有用户界面是块..
那么,我如何能够在不同的线程中放置和启动连接,
并在UIThread中执行OnResponse()/ OnErrorResponse()
JsonArrayRequest getReq = new JsonArrayRequest(url,new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d("onRESPONSE Synchro -> Produit",response.toString());
PgrBarProducts.setMax(response.length());
percentdisplayProduct.setText("0/"+ PgrBarProducts.getMax());
nbMaxCallNetwork = PgrBarProducts.getMax();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject explrObject = response.getJSONObject(i);
String id = Integer.toString((Integer) explrObject.get("id"));
callOneObject(id,PgrBarProducts,percentdisplayProduct,1); // appel du product
}
} catch (JSONException e) {
e.printstacktrace(new PrintWriter(stackTrace));
}
}
},new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
changeStatutToError();
VolleyLog.d("","Error: " + error.getMessage());
percentdisplayProduct.setTextColor(Color.RED);
percentdisplayProduct.setTypeface(null,Typeface.BOLD);
percentdisplayProduct.setText("erreur");
waitBarProgressproduct.setVisibility(View.INVISIBLE);
synchroProducts.setVisibility(View.VISIBLE);
}
});
getReq.setRetryPolicy(new DefaultRetryPolicy(60 * 1000,1,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue and start the request
AppController.getInstance().addToAndStartRequestQueue(getReq);
}
});
解决方法
每个由Volley执行的网络请求都是在后台线程中执行的. Volley在幕后照顾这个.所以没有必要在不同的线程上执行一个请求,因为已经在发生.
另一方面,听众在UI线程上被调用.
当您写入数据在UI线程上处理时,您基本上回答了自己的问题.只需将在侦听器中执行的数据处理移动到后台线程/ AsyncTask以释放您的UI线程并防止阻止.