Android-Volley网络通信框架

来源:互联网 发布:linux建立文件 编辑:程序博客网 时间:2024/05/01 19:01

1.回顾

       上篇对 Volley进行了简单介绍和对它的学习目的与目标,最后,为学习Volley做了一些准备


2.重点

      2.1 RequestQueue 请求队列的建立

      2.2 学习 StringRequest和JsonObjectRequest ;


3.RequestQueue 请求队列的建立

       新建类 volleyApplication 继承自Application , 使用单例模式创建 请求处理队列, 实现如下:


[java] view plaincopy
  1. package com.example.volleyHttp;  
  2.   
  3. import com.android.volley.RequestQueue;  
  4. import com.android.volley.toolbox.Volley;  
  5.   
  6. import android.app.Application;  
  7.   
  8. public class volleyApplication extends Application {  
  9.   
  10.     /** 
  11.      * 01. 建立  请求队列 
  12.      * 02. 将 请求队列 加入到 AndroidMain.xml中 
  13.      * 03.  
  14.      */  
  15.       
  16.     private static RequestQueue queue;  
  17.       
  18.     @Override  
  19.     public void onCreate() {  
  20.         // TODO Auto-generated method stub  
  21.         super.onCreate();  
  22.         queue=Volley.newRequestQueue(getApplicationContext());  
  23.     }  
  24.       
  25.     //入口  
  26.     public static RequestQueue getQueue(){  
  27.         return queue;  
  28.     }  
  29.       
  30.       
  31. }  

     这个可以与Activity 发生联动作用,在Activity 退出的时候,可以取消的 网络请求操作(通过 tag实现);下面可以实现:

[java] view plaincopy
  1. @Override  
  2. protected void onStop() {  
  3.     // TODO Auto-generated method stub  
  4.     volleyApplication.getQueue().cancelAll("strReqGet");  
  5.     super.onStop();  
  6. }  


      使用的时候需要在 AndroidMainfist.xml 文件里 的 Application 标签下 注册 刚才的 volleylication:

[html] view plaincopy
  1. <application  
  2.         android:allowBackup="true"  
  3.         android:icon="@drawable/ic_launcher"  
  4.       <span style="color:#ff0000;">  android:name="com.example.volleyHttp.volleyApplication"</span>  
  5.         android:label="@string/app_name"  
  6.         android:theme="@style/AppTheme" >  
  7.         <activity  
  8.             android:name=".MainActivity"  
  9.             android:label="@string/app_name" >  
  10.             <intent-filter>  
  11.                 <action android:name="android.intent.action.MAIN" />  
  12.   
  13.                 <category android:name="android.intent.category.LAUNCHER" />  
  14.             </intent-filter>  
  15.         </activity>  
  16.     </application>  

  不要忘记了添加网络权限!


4.StringRequest 的get和post方法

   

     4.1 get 操作

      (1)实例化StringRequest 对象

           (2)设置参数:请求方式,URL地址,成功的返回调用,失败的返回调用;

           (3)给请求设置 tag,添加到刚才的请求队列 中!

[java] view plaincopy
  1. private void strRequest_get() {  
  2.     StringRequest request = new StringRequest(Method.GET,  
  3.             HttpPath.getSharedIfo(1), new Listener<String>() {  
  4.   
  5.                 @Override  
  6.                 public void onResponse(String response) {  
  7.                     // TODO Auto-generated method stub  
  8.                     Toast.makeText(getApplicationContext(), response,  
  9.                             Toast.LENGTH_SHORT).show();  
  10.                     tv.setText(response);  
  11.                 }  
  12.             }, new Response.ErrorListener() {  
  13.   
  14.                 @Override  
  15.                 public void onErrorResponse(VolleyError error) {  
  16.                     Toast.makeText(getApplicationContext(),  
  17.                             error.getMessage(), Toast.LENGTH_SHORT).show();  
  18.                 }  
  19.             });  
  20.   
  21.     request.setTag("strReqGet");  
  22.     <span style="color:#ff0000;">volleyApplication.getQueue().add(request);</span>  
  23. }  

      4.2 post 操作

           (1)实例化StringRequest 对象

           (2)设置参数:请求方式,URL地址,成功的返回调用,失败的返回调用;

           (3)Post提交的参数设置:重写 getParams 方法,返回Map集合,将自动调用;

           (4)请求设置 tag,添加到刚才的请求队列 中!


[java] view plaincopy
  1. /** 
  2.      * 01.2 String Requset post 提交数据 
  3.      */  
  4.     private void strRequest_post(){  
  5.         StringRequest stringRequest=new StringRequest(Method.POST,HttpPath.getSharedIfo_post(),new Listener<String>() {  
  6.   
  7.             @Override  
  8.             public void onResponse(String response) {  
  9.                 // 成功返回数据  
  10.                 tv.setText(response);  
  11.             }  
  12.         },new Response.ErrorListener() {  
  13.   
  14.             @Override  
  15.             public void onErrorResponse(VolleyError error) {  
  16.                 //出错  
  17.                 Toast.makeText(getApplicationContext(),  
  18.                         error.getMessage(), Toast.LENGTH_SHORT).show();  
  19.             }  
  20.         }){  
  21.             @Override  
  22.             protected Map<String, String> getParams() throws AuthFailureError {  
  23.                 // post 提交 重写参数 ,将自动 提交参数  
  24.                 Map<String,String> map=new HashMap<String, String>();  
  25.                 map.put("id","2");  
  26.                 return map;  
  27.             }  
  28.         };  
  29.           
  30.         stringRequest.setTag("strPost");  
  31.         volleyApplication.getQueue().add(stringRequest);  
  32.           
  33.     }  


5.JsonObjectRequest 的 get和post方法

     5.1 get 方法

           (1)实例化JsonObjectRequest 对象

           (2)设置参数:请求方式,URL地址,参数Jsonrequest 为 null (因为为get请求),成功的返回调用,失败的返回调用;

           (3)给请求设置 tag,添加到刚才的请求队列 中!

           (4)请求成功后,直接返回 成 JsonObject 对象 ,可以直接使用


[java] view plaincopy
  1. /** 
  2.  * 02.jsonobjectRequert get请求 
  3.  */  
  4. private void jsonRequest_get(){  
  5.     JsonObjectRequest objectRequest=new JsonObjectRequest(Method.GET,HttpPath.getSharedIfo(1),  
  6.             null,new Listener<JSONObject>() {  
  7.   
  8.                 @Override  
  9.                 public void onResponse(JSONObject response) {  
  10.                     //直接进行 json解析  
  11.                     try {  
  12.                         JSONObject jsonObject=new JSONObject(response.getString("data"));  
  13.                         tv.setText(jsonObject.getString("note"));  
  14.                     } catch (JSONException e) {  
  15.                         // TODO Auto-generated catch block  
  16.                         tv.setText(e.getMessage());  
  17.                     }  
  18.                 }  
  19.             },new Response.ErrorListener() {  
  20.   
  21.                 @Override  
  22.                 public void onErrorResponse(VolleyError error) {  
  23.                     //请求失败返回的信息  
  24.                     tv.setText(error.getMessage());  
  25.                 }  
  26.             });  
  27.     objectRequest.setTag("jsonRequest");  
  28.     volleyApplication.getQueue().add(objectRequest);  
  29. }  

      5.2 post 方法

           (1)实例化JsonObjectRequest 对象

           (2)设置参数:请求方式,URL地址,参数JsonRequest ,成功的返回调用,失败的返回调用;

           (3)请求参数设置:通过 JsonObejct 实现 post提交 参数设置 (见示例代码)

           (4)给请求设置 tag,添加到刚才的请求队列 中!

           (5)请求成功后,直接返回 成 JsonObject 对象 ,可以直接使用

[java] view plaincopy
  1. /** 
  2.  * 02.2 jsonObjectRequest post的方式 请求 
  3.  */  
  4.   private void jsonRequest_post(){  
  5.      
  6.   <span style="color:#ff0000;"//封装请求参数 </span>  
  7.    JSONObject jsonStr=new JSONObject();  
  8.    try {  
  9.     jsonStr.put("id","2");  
  10. catch (JSONException e1) {  
  11.     // TODO Auto-generated catch block  
  12.     e1.printStackTrace();  
  13. }  
  14.      
  15.    JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Method.POST,HttpPath.getSharedIfo_post()  
  16.            ,jsonStr, new Listener<JSONObject>() {  
  17.   
  18.             @Override  
  19.             public void onResponse(JSONObject response) {  
  20.                 // TODO Auto-generated method stub  
  21.                 JSONObject jsonObject;  
  22.                 try {  
  23.                     jsonObject = new JSONObject(response.getString("data"));  
  24.                     tv.setText(jsonObject.getString("note"));  
  25.                 } catch (JSONException e) {  
  26.                     // TODO Auto-generated catch block  
  27.                     e.printStackTrace();  
  28.                 }  
  29.                   
  30.             }  
  31.         },new Response.ErrorListener() {  
  32.   
  33.             @Override  
  34.             public void onErrorResponse(VolleyError error) {  
  35.                 // TODO Auto-generated method stub  
  36.                 tv.setText(error.getMessage());  
  37.             }  
  38.         });  
  39.    jsonObjectRequest.setTag("jsonPost");  
  40.    volleyApplication.getQueue().add(jsonObjectRequest);  
  41.      
  42.      
  43.   }  


6.JsonArrayRequest 

    这个我就不在累赘了,和 JsonObjectResquest 一样 , 只不过返回的是 JsonArray 类型!

7. 注意 

    RequestQueue 请求队列 在初始化的时候,一定要在 android 配置文件的Application 标签里进行注册!

   使用的时候,注意 导入 包问题,ErrorListener 一定是 Response.ErrorListener;


8.ImageRequest  

    (1)实例化 ImageRequest 对象

    (2)设置参数 :这里的HttpPath.getPic() 是 URL图片地址

    (3)请求成功后,回调 bitmap对象 直接可以赋值给 ImageView

    (4)需要在 请求处理队列中执行

    (5)默认图片可以在加载前设置好,错误图片可以在出错的时候设置

[java] view plaincopy
  1.         /** 
  2.  * 03. imageRequest 请求一张图片 
  3.  */  
  4. private void imageRequest_get(){  
  5.     ImageRequest imageRequest=new ImageRequest(HttpPath.getPic(),  
  6.     new Response.Listener<Bitmap>() {  
  7.   
  8.   
  9.         @Override  
  10.         public void onResponse(Bitmap response) {  
  11.             // TODO Auto-generated method stub  
  12.             imageView1.setImageBitmap(response);  
  13.         }  
  14.     },0,0,Config.RGB_565,new Response.ErrorListener() {  
  15.   
  16.   
  17.         @Override  
  18.         public void onErrorResponse(VolleyError error) {  
  19.             // TODO Auto-generated method stub  
  20.             tv.setText(error.getMessage());  
  21.         }  
  22.     });  
  23.     imageRequest.setTag("iamgerequest");  
  24.     volleyApplication.getQueue().add(imageRequest);  
  25.       
  26. }  


9. ImageLoader 的使用

     9.1优点

      (1) 可以设置 出错的时候,显示的图片和设置默认图片!

      (2) 图片缓存的实现

     9.2 无缓存实现 加载一张图片

[java] view plaincopy
  1. /** 
  2.      * 4.imageloader  ,无缓存的 
  3.      * 优点是:图片缓存技术 
  4.      */  
  5.     private void imageLoader_get(){  
  6.           
  7.         //设置 图片缓存 这里为 空的,没有使用 缓存  
  8.         ImageCache cache=new ImageCache() {  
  9.               
  10.             @Override  
  11.             public void putBitmap(String url, Bitmap bitmap) {  
  12.                 // 没有  
  13.                   
  14.             }  
  15.               
  16.             @Override  
  17.             public Bitmap getBitmap(String url) {  
  18.                 // 没有  
  19.                 return null;  
  20.             }  
  21.         };  
  22.         //实例化对象  
  23.         ImageLoader imageLoader=new ImageLoader(volleyApplication.getQueue(),cache);  
  24.         // 图片监听 (默认图片,错误图片) 和 imageView  
  25.         ImageListener imageListener=ImageLoader.getImageListener(imageView1,R.drawable.ic_launcher,R.drawable.ic_launcher);  
  26.           
  27.         //加载图片  
  28.         imageLoader.get(HttpPath.getPic(),imageListener,0,0);  
  29.           
  30.     }  

      9.3 ImageLoader+LruCache 实现图片的加载和缓存

          (1)实现ImageCache :这里新建一个类,继承自ImgaeCache

[java] view plaincopy
  1. package com.example.Util;  
  2.   
  3. import android.annotation.SuppressLint;  
  4. import android.graphics.Bitmap;  
  5. import android.util.LruCache;  
  6. import com.android.volley.toolbox.ImageLoader.ImageCache;  
  7.   
  8. @SuppressLint("NewApi")  
  9. public class BitmapCache implements ImageCache{  
  10.   
  11.     //使用LruCache 实现图片缓存 :  
  12.     //使用地址:  
  13.     //http://blog.csdn.net/guolin_blog/article/details/9316683  
  14.   
  15.     private LruCache<String,Bitmap> cache;  
  16.     //设置最大的 尺寸值  
  17.       
  18.     public BitmapCache() {  
  19.         //构造方法 实现 LruCache 缓存 图片  
  20.           
  21.         int maxSize=10*1024*1024;  
  22.         cache=new LruCache<String,Bitmap>(maxSize){  
  23.             @Override  
  24.             protected int sizeOf(String key, Bitmap value) {  
  25.                 return value.getRowBytes()*value.getHeight();  
  26.             }  
  27.         };  
  28.           
  29.     }  
  30.       
  31.     @Override  
  32.     public Bitmap getBitmap(String url) {  
  33.         // 得到  
  34.         return cache.get(url);  
  35.     }  
  36.   
  37.     @Override  
  38.     public void putBitmap(String url, Bitmap bitmap) {  
  39.         // 设置  
  40.         cache.put(url, bitmap);  
  41.     }  
  42.   
  43. }  

      (2)下面实现调用即可:

[java] view plaincopy
  1. /** 
  2.  * 4.2 将 imageLoader和 缓存联系在一起! 
  3.  */  
  4. private void imageLoader_cache(){  
  5.       
  6.     //设置 图片缓存 :体现 imageLoader的优势  
  7.         //使用 LruBitmap + ImageCache 实现   
  8.     //实例化对象  
  9.     ImageLoader imageLoader=new ImageLoader(<span style="color:#ff0000;">volleyApplication.getQueue(),new BitmapCache()</span>);  
  10.     // 图片监听 (默认图片,错误图片) 和 imageView  
  11.     ImageListener imageListener=ImageLoader.getImageListener(imageView1,R.drawable.ic_launcher,R.drawable.ic_launcher);  
  12.       
  13.     //加载图片  
  14.     imageLoader.get(HttpPath.getPic(),imageListener,0,0);  
  15.       
  16. }  

10.ImageLoader+NetWorkImageView 实现图片获取

    (1)首先在布局文件里新添加 NetworkImageView 布局

[html] view plaincopy
  1. <com.android.volley.toolbox.NetworkImageView     
  2.       android:id="@+id/network_image_view"    
  3.       android:layout_width="200dp"    
  4.       android:layout_height="200dp"    
  5.       android:layout_gravity="center_horizontal"    
  6.       />   

    (2)初始化 控件

            使用findViewByid  实现

    (3)使用

      这个方法是 传进来 图片名称,后通过Url 从服务器获取!很简单,需要实例化 ImageLoader;

[java] view plaincopy
  1. /** 
  2.      * 4.3 使用networkImageView 加载图片 
  3.      */  
  4.     private void networkImageview_get(String pic){  
  5.           
  6.         <span style="color:#ff0000;">ImageLoader imageLoader=new ImageLoader(volleyApplication.getQueue(),new BitmapCache());</span>  
  7.           
  8.         network_image_view.setDefaultImageResId(R.drawable.ic_launcher);  
  9.         network_image_view.setErrorImageResId(R.drawable.ic_launcher);  
  10.         network_image_view.setImageUrl(HttpPath.getBasicPath()+"/"+pic,imageLoader);  
  11.           
  12.     }  

1 0
原创粉丝点击