光头强_Mr

博客园 首页 联系 订阅 管理
 
                                                                         Volley
 
学习笔记
如有错误之处请大家帮忙指出纠正__谢谢
-------------------------------------------------------------------------------------------------------------------------------------------
 
 
 
 
一 : Volley概述 
 

 
------------------------------------------------------------
框架功能介绍
 
1 Volley的get和post请求方式使用 : 
我们进行请求之前 , 要挑选请求对象, 确定请求的数据返回的类型是哪个Volley自带三种 : 
[1]针对请求数据返回类型不确定时使用 : StringRequest  
[2]确定返回数据是JsonObject类型 时使用 : JsonObjectRequest   
[3]确定返回数据是JsonArray类型 时使用 :  JsonArrayRequest
根据返回数据的类型 , 进行合适对象的挑选
---------------------------------------
我们已经掌握了Volley各种Request的使用方法,包括StringRequest、JsonRequest、ImageRequest等。其中StringRequest用于请求一条普通的文本数据,JsonRequest(JsonObjectRequest、JsonArrayRequest)用于请求一条JSON格式的数据,ImageRequest则是用于请求网络上的一张图片。
---------------------------------------
 
 
回调类使用
 
2 Volley的网络请求队列建立和取消队列请求
使用Volley之前需要建立请求队列
将请求加入到全局队列中,这样我们整个app请求通过整个队列来进行管理 , 
方便取消某个请求 , 或者取消整个请求
 
 
3 Volley与Activity生命周期的联动
特点 , Volley请求的声明周期与Activity的声明周期是关联在一起的 , 加入Activity销毁, 我们的请求也可以同时让他进行销毁 (防止在后台运行这个请求,导致内存溢出或者用户体验不好)
一般关联的时候,都设置Tag标签 , 在Activity的onStop( ) 中通过标签取消请求
 
 
4 Volley的简单的二次回调封装
使用自定义的 , 便于全局管理 , 加入我们在请求开始弹出对话框 , 请求结束 , 结束对话框 
优势 : 
全局使用一个方式 , 可控,灵活
 
 
----------------------------------------------------
 
二 : 网络数据请求 , 
1 使用get方式请求数据 
 
代码实例 : 
jar包拷贝到libs目录下
 
 [1] 我们需要建立请求队列 , 该请求队列需要是全局的 
       将请求队列建立在Application 子类中 
  1.  1 package com.timliu.volleyactivity;
     2 
     3 import android.app.Application;
     4 
     5 import com.android.volley.RequestQueue;
     6 import com.android.volley.toolbox.Volley;
     7 
     8 /**
     9  * Created by tim2 on 15/8/9.
    10  */
    11 public class MyApplication extends Application
    12 {
    13     public static RequestQueue queues;
    14 
    15     @Override
    16     public void onCreate() {
    17         super.onCreate();
    18         queues = Volley.newRequestQueue(getApplicationContext());
    19     }
    20 
    21     public static RequestQueue getHttpQueues()
    22     {
    23         return queues;
    24     }
    25 }
    View Code

     

     将其注册到清单文件中 , 加网络权限
     
  
  [2]使用stringRequest请求对象 , 请求数据接口
       建立请求对象
        选第二个构造  (参1 请求方式 ; 参2 url地址 ; 3请求成功回调new Listener( ) ; 4请求失败回调new Response.ErrorListener( )  )
 
        url : 
               get携带参数
 
  [3]给请求对象设置Tag标签 
   request.setTag("自定义abcGet");
 
  [4]将request添加到全局队列中
      先获取队列 , 进行添加
       
     
       例子:
     
-----------------
  使用JsonObjectRequest请求 第二个构造
  参1 请求方式get/post 
 
  参2 url
 
  参3 jsonObject [get方式请求,请求参数直接在url地址中写好了,传null就可以了;post 方式 这里需要传递附带请求参数的JsonObject]
 
  参4 请求成功回调  [同上]
 
  参5 请求失败回调  [同上]
 
 
 
2 使用post方式请求数据 
   [1]StringRequest
   post url中 参数不能直接写在url中 , 需要使用参数化的传递 ,
 
              
 
 
  post请求在Volley中需要单独实现传递参数的方法 , 将参数添加到集合中
   new  StringRequest(  构造参数.... ){ getParams() { code... } }
   
 
 请求的时候 , volley会自动调用集合中的参数
 
 [2]JsonObjectRequest请求 , 这里我们只需改动参数3,将参数添加进去  传递JSONObject对象 , 会自动调用传递进去的参数,进行请求
      
 
 
 
三 : Volley与Activity联动
 
 
 
 
四 : Volley简单的二次回调封装
 
      理解了volley的get post简单的请求方式之后 , 我们可以模仿他, 对我们的volley进行简单封装
      封装的就是 请求成功 失败关键的回调 
 
[1]创建自己的请求管理 
采用StringRequest讲解
 
 
 1 package utils;
 2 
 3 import android.content.Context;
 4 
 5 import com.android.volley.AuthFailureError;
 6 import com.android.volley.Request;
 7 import com.android.volley.toolbox.StringRequest;
 8 import com.timliu.volleyactivity.MyApplication;
 9 
10 import java.util.Map;
11 
12 
13 public class VolleyRequest
14 {
15     public static StringRequest stringRequest;
16     public static Context context;
17 
18     public static void RequestGet(Context context,String url, String tag, VolleyInterface vif)
19     {
20 
21         MyApplication.getHttpQueues().cancelAll(tag);
22         stringRequest = new StringRequest(Request.Method.GET,url,vif.loadingListener(),vif.errorListener());
23         stringRequest.setTag(tag);
24         MyApplication.getHttpQueues().add(stringRequest);
25         // 不写也能执行
26 //        MyApplication.getHttpQueues().start();
27     }
28 
29     public static void RequestPost(Context context,String url, String tag,final Map<String, String> params, VolleyInterface vif)
30     {
31         MyApplication.getHttpQueues().cancelAll(tag);
32         stringRequest = new StringRequest(Request.Method.POST,url,vif.loadingListener(),vif.errorListener())
33         {
34             @Override
35             protected Map<String, String> getParams() throws AuthFailureError {
36                 return params;
37             }
38         };
39         stringRequest.setTag(tag);
40         MyApplication.getHttpQueues().add(stringRequest);
41         // 不写也能执行
42 //        MyApplication.getHttpQueues().start();
43     }
44 }
View Code

 

建立抽象类 , 用来封装 请求成功 , 失败的回调方法
 1 package utils;
 2 
 3 import android.content.Context;
 4 
 5 import com.android.volley.Response;
 6 import com.android.volley.VolleyError;
 7 
 8 import org.json.JSONException;
 9 
10 
11 public abstract class VolleyInterface
12 {
13     public Context context;
14     public static Response.Listener<String> listener;
15     public static Response.ErrorListener errorListener;
16 
17     public abstract void onMySuccess(String result);
18     public abstract  void onMyError(VolleyError error);
19 
20     public VolleyInterface (Context context, Response.Listener<String> listener, Response.ErrorListener errorListener)
21     {
22         this.context = context;
23         this.listener = listener;
24         this.errorListener = errorListener;
25     }
26 
27     public Response.Listener<String> loadingListener()
28     {
29         listener = new Response.Listener<String>() {
30             @Override
31             public void onResponse(String response) {
32                 onMySuccess(response);
33             }
34         };
35         return listener;
36     }
37 
38     public Response.ErrorListener errorListener()
39     {
40         errorListener = new Response.ErrorListener() {
41             @Override
42             public void onErrorResponse(VolleyError error) {
43                 onMyError(error);
44             }
45         };
46         return errorListener;
47     }
48 }
View Code
  
 改造之前MainActivity中代码使用封装后的访问网络 : 
 
 
 
五 : 使用ImageRequest获取网络图片
 
                               
   
方式1 : 使用volley的ImageRequest加载网络图片
 1  String url = "http://h.hiphotos.baidu.com/image/pic/item/d53f8794a4c27d1e3584e91b1fd5ad6edcc4384b.jpg";
 2          //参1 url;  参2 访问网络成功返回的bitmap对象; 参3 4设置图片显示的大小[0,0表示图片多大就显示多大] ;参5 加载图片的格式;参6加载失败回调 
 3         ImageRequest request = new ImageRequest(url, new Response.Listener<Bitmap>() {
 4             @Override
 5             public void onResponse(Bitmap response) {
 6                 textview.setText("获取图片成功");
 7                 imageView.setImageBitmap(response);
 8             }
 9         }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
10             @Override
11             public void onErrorResponse(VolleyError error) {
12                 textview.setText("获取图片错误");
13                 imageView.setImageBitmap(null);
14             }
15         });
16         
17         //将请求添加到队列中
18         MyApplication.getHttpQueues().add(request);
View Code

 

方式2 :  使用Volley中的ImageLoader加载图片

      通过普通的imageView
     结合缓存 ImageCache + LruCache 
                                                                +ImageLoader+imageListener
 
  
    ImageCache 单独使用起不到缓存效果, 需要结合LruCache 才可以
   自定义BitmapCache implement ImageCache 
 1 package utils;
 2 
 3 import android.graphics.Bitmap;
 4 import android.util.LruCache;
 5 
 6 import com.android.volley.toolbox.ImageLoader;
 7 
 8 /**
 9  * Created by tim2 on 15/8/11.
10  */
11 public class BitmapCache implements ImageLoader.ImageCache
12 {
13     public LruCache<String, Bitmap> cache;
14     public int max = 10*1024*1024; // 10M图片大小
15 
16     public BitmapCache()
17     {
18         cache = new LruCache<String, Bitmap>(max){
19             @Override
20             protected int sizeOf(String key, Bitmap value)
21             {
22                 return value.getRowBytes() * value.getHeight();
23             }
24         };
25     }
26 
27     @Override
28     public Bitmap getBitmap(String url) {
29         return cache.get(url);
30     }
31 
32     @Override
33     public void putBitmap(String url, Bitmap bitmap) {
34         cache.put(url, bitmap);
35     }
36 }
View Code

 

    
 
 
开始访问网络
  1. 1  String url = "http://g.hiphotos.baidu.com/image/pic/item/21a4462309f790521631d9e908f3d7ca7bcbd53f.jpg";
    2         //使用ImageLoader请求  参1 请求队列; 参2 缓存对象
    3         ImageLoader loader = new ImageLoader(MyApplication.getHttpQueues(), new BitmapCache());
    4         //访问监听 参1 要绑定的控件; 参2 未加载网络图片之前默认显示图片; 参3访问网络失败显示图片
    5         ImageLoader.ImageListener listener = ImageLoader.getImageListener(imageView, R.drawable.default_icon , R.drawable.error );
    6         //访问网络
    7         loader.get(url, listener);
    View Code
 
方式3 : 使用Volley的 
xml设置 :  networkImageView = (NetworkImageView) findViewById(R.id.networkImageView);
  1. 1  String url = "http://g.hiphotos.baidu.com/image/pic/item/0ff41bd5ad6eddc487907ddd3cdbb6fd526633a5.jpg";
    2         textview.setText("获取NetworkImageView图片开始了");
    3         imageView.setImageBitmap(null);
    4         ImageLoader loader = new ImageLoader(MyApplication.getHttpQueues(), new BitmapCache());
    5         networkImageView.setErrorImageResId(R.drawable.error2);
    6         networkImageView.setDefaultImageResId(R.drawable.default_icon);
    7         networkImageView.setImageUrl(url, loader);
    View Code

     


 
 
 

 

posted on 2015-12-21 23:14  光头强_Mr  阅读(247)  评论(0编辑  收藏  举报