我想在另一个线程中使用Android Volley库发出请求.
I would like to make a request using the Android Volley library in a different thread.
我的意思是,线程中存在连接并且UI线程中处理了数据.
What I mean is, there is the connection which is in the thread and the data is processed in the UI thread.
我想这样做是因为我有很多连接,要处理的数据很多,现在用户界面被阻止了.
I want to do this because I have a lot of connections, a lot of data to process, and right now the user interface is blocked.
因此,如何在不同的线程中创建和启动连接, 然后在UIThread中执行OnResponse()/OnErrorResponse()吗?
So, how do I create and start the connection in a different Thread, and do then OnResponse()/OnErrorResponse() in the UIThread?
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执行的每个网络请求都在后台线程中执行.凌空在幕后照顾这件事.因此,无需在其他线程上执行请求,因为这种情况已经发生.
Every network request performed by Volley is performed in a background thread. Volley takes care of this behind the scenes. So there is no need to perform a request on a different thread, since that's already happening.
另一方面,在UI线程上调用了侦听器.
The listeners, on the other hand, are called on the UI thread.
当您写到数据是在UI线程上处理时,您基本上回答了自己的问题.只需将在侦听器内部执行的数据处理移至后台线程/AsyncTask,以释放UI线程并防止阻塞.
You basically answered your own question when you wrote that the data is processed on the UI thread. Simply move that data processing that is performed inside your listeners to a background thread / AsyncTask to free your UI thread and prevent the blocking.
更多推荐
在不同线程中发出Volley请求
发布评论