volley框架理解

 今天被问道volley框架,这东西,只用过,还真不知道怎么实现的,我说一个晚上搞定。哈哈,看完了,写篇日志整理整理.
    
首先,初始化volley,最好在 Application的onCreate方法中初始化。
         RequestQueue mRequestQueue = Volley.newRequestQueue(this);
      //这个RequestQueue是volley对外开提供的一个队列,用于存放用户请求的。具体内部实现,听我慢慢给你道来。
其次,volley的使用:
          JsonObjectRequest jr = new JsonObjectRequest(Request.Method.GET,url,null,new Response.Listener<JSONObject>() {  
            @Override  
            public void onResponse(JSONObject response) {  
                Log.i(TAG,response.toString());  
                //todo  拿到了
            }  
        },new Response.ErrorListener() {  
            @Override  
            public void onErrorResponse(VolleyError error) {  
                Log.i(TAG,error.getMessage());  
            }  
        });  
        mRequestQueue.add(jr);​
        //代码没有什么好解释的把,把一个JsonObjectRequest放入 RequestQueue中,JsonObjectRequest构造中完成onReponse和ErrorListener的回调即可。
        //在回调用写入对数据的处理。
​    
来说说volley的框架把。
先要来介绍volley中的几个概念:
Request:Base class for all network requests.  //网络请求的基类。其子类有: 
            StringRequest: A canned request for retrieving the response body at a given URL as a String.​ //请求的URL数据解析为String字符串
            ImageRequest: A canned request for getting an image at a given URL and calling back with a decoded Bitmap.//请求URL获得bitmap数据
            JsonRequest : Json请求的基类
                    JsonObjectRequest
​                     JsonArrayRequest​
Dispatcher:首先他是一个线程,​死循环处理数据,除非此线程被中断了。volley有两个dispatcher,分别是:
            CacheDispatcher,NetworkDispatcher
​ResponseDelivery:其实是一个接口,有postResponse,postError方法,而子类ExecutorDelivery实现了这些方法,通过handler将数据发送给了主线程。
DiskBasedCache:volley实现的本地磁盘缓存。
 
 
其架构如下,(盗网上一张图),不过我还有补充。volley.png
​​​​
        默认情况下,咱们的Request的mShouldCache属性为true,也就是说一般的请求都发给了CacheDispatcher。
        CacheDispatcher和NetworkDispatcher都关联着DiskBasedCache,当从CacheDispatcher中取请求时,会从​DiskBasedCache中找,找不到的话或者请求已经过期,就将此request也加入网络请求的队列中。如果CacheDispatcher在缓存中找到数据,就​调用ExecutorDelivery将数据发给主线程。​
        而NetworkDispatcher就简单了,直接请求网络,请求回来的数据,​通过ExecutorDelivery将数据发给主线程。​
posted @ 2015-07-21 23:44  fangtest  阅读(153)  评论(0)    收藏  举报