Volley使用了線程池來做爲基礎結構,主要分爲主線程,cache線程和network線程。主線程和cache線程都只有一個,而NetworkDispatcher線程能夠有多個,這樣能解決比並行問題。具體能夠參考下圖,此圖節選自Google I/O 演講。html
引入Volley很是簡單,首先,從git庫先克隆一個下來:java
git clone https://android.googlesource.com/platform/frameworks/volley
而後編譯爲jar包,再在本身的工程裏import進來。若是git下載失敗能夠在這下載。 VolleyLibandroid
mRequestQueue = Volley.newRequestQueue(this); String url = "http://pipes.yahooapis.com/pipes/pipe.run?_id=giWz8Vc33BG6rQEQo_NLYQ&_render=json"; pd = ProgressDialog.show(this,"Please Wait...","Please Wait..."); JsonObjectRequest jr = new JsonObjectRequest(Request.Method.GET,url,null,new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.i(TAG,response.toString()); parseJSON(response); va.notifyDataSetChanged(); pd.dismiss(); } },new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.i(TAG,error.getMessage()); } }); mRequestQueue.add(jr);
RequestQueue mRequestQueue = Volley.newRequestQueue(this); final LruCache<String, Bitmap> mImageCache = new LruCache<String, Bitmap>( 20); ImageCache imageCache = new ImageCache() { @Override public void putBitmap(String key, Bitmap value) { mImageCache.put(key, value); } @Override public Bitmap getBitmap(String key) { return mImageCache.get(key); } }; ImageLoader mImageLoader = new ImageLoader(mRequestQueue, imageCache); // imageView是一個ImageView實例 // ImageLoader.getImageListener的第二個參數是默認的圖片resource id // 第三個參數是請求失敗時候的資源id,能夠指定爲0 ImageListener listener = ImageLoader .getImageListener(imageView, android.R.drawable.ic_menu_rotate, android.R.drawable.ic_delete); mImageLoader.get("http://a.hiphotos.baidu.com/album/h%3D800%3Bcrop%3D0%2C0%2C1280%2C800/sign=5f024b518326cffc762ab2b2893a29e2/72f082025aafa40fa3bcf315aa64034f79f019fb.jpg", listener);
NetworkImageView是繼承自ImageView,是Volley提供的一個全新的簡單加載圖片的控件。git
NetworkImageView netImgView=(NetworkImageView)findViewById(R.id.volley_img_networkimgeview); netImgView.setTag("url"); netImgView.setImageUrl("http://a.hiphotos.baidu.com/album/h%3D800%3Bcrop%3D0%2C0%2C1280%2C800/sign=5f024b518326cffc762ab2b2893a29e2/72f082025aafa40fa3bcf315aa64034f79f019fb.jpg",mImageLoader);
參考:web
Google I/O 2013 – Volley: Easy, Fast Networking for Android(ppt)api