在不同的线程中制作排球请求

Tho*_*lsi 14 java multithreading android request android-volley

我想在不同的Thread中使用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);

Run Code Online (Sandbox Code Playgroud)

Ita*_*ski 20

Volley执行的每个网络请求都在后台线程中执行.Volley在幕后处理这个问题.因此,不需要在不同的线程上执行请求,因为这已经发生了.

另一方面,侦听器在UI线程上调用.

当您写下在UI线程上处理数据时,您基本上回答了自己的问题.只需将在侦听器内执行的数据处理移动到后台线程/ AsyncTask即可释放UI线程并防止阻塞.