• android之Volley框架的使用(1)


    1.volley的get和post请求数据方式的使用

         StringRequest(对返回数据类型不确定的情况下)包含后两种

         JsonObjectRequest

         JsonArrayRequest

         回调使用,,成功,失败

      Get方式获取数据

       StringRequest request = new StringRequest(Method.GET, url, new Listener<String>() {
               public void onResponse(String response) {   //数据请求成功返回到这个里面
                      //对response解析即可			
    	}
    	   }, new Response.ErrorListener() {
    
    			
    	   public void onErrorResponse(VolleyError error) {   //数据 请求失败返回到这个里面
    				}
    	   });
    	request.setTag("successGet");
    	MyApplication.getHttpQueues().add(request);
          后面两个和这个是差不多的

     Post请求获取数据    

      StringRequest

      StringRequest request = new StringRequest(Method.POST, url, new Listener<String>() {
    
    			@Override
    			public void onResponse(String response) {   //数据请求成功返回到这个里面
    				// TODO Auto-generated method stub
    				
    			}
    		}, new Response.ErrorListener() {
    
    			@Override
    			public void onErrorResponse(VolleyError error) {   //数据 请求失败返回到这个里面
    				// TODO Auto-generated method stub
    				
    			}
    		}){
    		protected Map<String, String> getParams() throws AuthFailureError {//post和get不一样的地方
    			// TODO Auto-generated method stub
    			
    			Map<String,String> hashMap = new HashMap<String,String>();
    			hashMap.put("phone", "15671654057");
    			hashMap.put("key", "**");
    			return hashMap;
    		}};
    		request.setTag("successPost");
    		MyApplication.getHttpQueues().add(request);
      JsonObjectRequest

       

    		HashMap<String,String>map = new HashMap<String,String>();
    		map.put("phone", "15671654057");
                    map.put("key", "**");             //这里的key我是用的聚合
    		JSONObject object = new JSONObject(map);
    		JsonObjectRequest objectRequest = new JsonObjectRequest(Method.POST, url, object , new Listener<JSONObject>() {
    
    			@Override
    			public void onResponse(JSONObject response) {
    				// TODO Auto-generated method stub
    				
    			}}, new Response.ErrorListener() {
    
    			@Override
    			public void onErrorResponse(VolleyError error) {
    				// TODO Auto-generated method stub
    				
    			}
    		});
    		objectRequest.setTag("successPost");
    		MyApplication.getHttpQueues().add(objectRequest);
    		


    2.volley的网络请求队列建立和取消队列请求

         建立全局请求队列

         

    public class MyApplication extends Application {
    
    	public static RequestQueue queues;
    	@Override
    	public void onCreate() {
    		// TODO Auto-generated method stub
    		super.onCreate();
    		queues = Volley.newRequestQueue(getApplicationContext());
    		
    	}
    	public static RequestQueue getHttpQueues()  //获取请求队列
    	{
    		return queues;
    	}
    }


    3.volley与activity生命周期的联动

        activity销毁,同时关闭请求

       设置tag标签,onStop()丽执行取消请求

        

    protected void onStop() {
        	// TODO Auto-generated method stub
        	super.onStop();
        	MyApplication.getHttpQueues().cancelAll("successGet");   //与Activity生命周期绑定
        }

    4.volley的简单的二次回调封装

       使用自己定义的,使用一个全局可控的

       

    public abstract class VolleyInterface {
    
    	public Context context;
    	public static Listener<String> mListener;
            public static ErrorListener mErrorListener;
    	public VolleyInterface(Context context , Listener<String> listener,
    			ErrorListener errorListener) {
    		// TODO Auto-generated constructor stub
    		
    		this.context = context;
    		this.mListener = listener;
    		this.mErrorListener = errorListener;
    	}
    	
    	
    	public abstract void onMySuccess(String result);
    	public abstract void onMyError(VolleyError error);
    	public Listener<String> loadingListener()
    	{
    		mListener = new Listener<String>() {
    
    			@Override
    			public void onResponse(String response) {
    				// TODO Auto-generated method stub
    				onMySuccess(response);
    			}
    		};
    		return mListener;
    	}
    	
    	public ErrorListener errorListener()
    	{
    		mErrorListener = new ErrorListener()
    		{
    
    			@Override
    			public void onErrorResponse(VolleyError error) {
    				// TODO Auto-generated method stub
    				onMyError(error);
    			}
    			
    		};
    		return mErrorListener;
    	}
    }

      



      public class VolleyRequest {
    
    	public static StringRequest stringRequest;
    	public static Context context;
    	public static void RequestGet(Context mContext,String url,String tag,
    			VolleyInterface vif) //vif,请求回调接口
    	{
    		MyApplication.getHttpQueues().cancelAll(tag);//防止进行重复请求
    		stringRequest = new StringRequest(Method.GET, url, vif.loadingListener() , vif.errorListener() );
    		stringRequest.setTag(tag);
    		MyApplication.getHttpQueues().add(stringRequest);
    		MyApplication.getHttpQueues().start();
    	}
    	public static void RequestPost(Context context , String url ,String tag ,final Map<String,String> params,VolleyInterface vif)
    	{
    		MyApplication.getHttpQueues().cancelAll(tag);
    		stringRequest = new StringRequest(url, vif.loadingListener(), vif.errorListener())
    		{
    			@Override
    			protected Map<String, String> getParams() throws AuthFailureError {
    				// TODO Auto-generated method stub
    				return params;
    			}
    		};
    	}
    }
    主activity里面就可以用我们自定义的了

    VolleyRequest.RequestGet(this, url, "successGet", new VolleyInterface(this,VolleyInterface.mListener,VolleyInterface.mErrorListener) {
    			
    			@Override
    			public void onMySuccess(String result) {
    				// TODO Auto-generated method stub
    				
    			}
    			
    			@Override
    			public void onMyError(VolleyError error) {
    				// TODO Auto-generated method stub
    				
    			}
    		});
    5.volley加载网络图片和监听

        LruCache                         

        ImageLoader                 

        NetworkImageView   

        


       最简单的

            ImageRequest request = new ImageRequest(url, new Listener<Bitmap>() {
    
    			@Override
    			public void onResponse(Bitmap response) {
    				// TODO Auto-generated method stub
    				iv_img.setImageBitmap(response);
    			}
    		}, 0, 0,//图片大小,00为默认的 Config.RGB_565//图片格式, new Response.ErrorListener() {
    
    			@Override
    			public void onErrorResponse(VolleyError error) {
    				// TODO Auto-generated method stub
    				
    			}
    		});
            MyApplication.getHttpQueues().add(request);
      另外一种,带缓冲机制

        

    public class BitmapCache implements ImageCache {
    
    	public LruCache<String,Bitmap> cache;
    	public int max = 10*1024*1024;    //最大缓冲内存大小,超过启动自动回收
    	public BitmapCache()
    	{
    		cache = new LruCache<String,Bitmap>(max)
    	        {
    			 protected int sizeOf(String key, Bitmap value) {
    			       return value.getRowBytes()*value.getHeight();//
    			 }
    		};
    	}
    	
    	@Override
    	public Bitmap getBitmap(String url) {
    		// TODO Auto-generated method stub
    		return cache.get(url);
    	}
    
    	@Override
    	public void putBitmap(String url, Bitmap bitmap) {
    		// TODO Auto-generated method stub
                   cache.put(url, bitmap);
    	}
    
    }


    主activity中


     ImageLoader loader = new ImageLoader(MyApplication.getHttpQueues(), new BitmapCache());
     ImageListener listener = ImageLoader.getImageListener(iv_img, R.drawable.ic_launcher, R.drawable.ic_launcher);//有一个图片是加载错误时显示
     loader.get(url, listener);
    </pre><pre name="code" class="html">



       是用volley自己的控件显示图片
       
    <com.android.volley.toolbox.NetworkImageView
             android:id="@+id/imag"
             android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_marginLeft="63dp"
            android:layout_toRightOf="@+id/textView1"
            
             ></com.android.volley.toolbox.NetworkImageView>
       

    主activity中

            netImageView = (NetworkImageView) findViewById(R.id.imag);
            ImageLoader loader = new ImageLoader(MyApplication.getHttpQueues(), new BitmapCache());
            
            netImageView.setDefaultImageResId(R.drawable.ic_launcher);//默认显示
            netImageView.setErrorImageResId(R.drawable.ic_launcher);  //加载错误显示
            netImageView.setImageUrl(url, loader);                    //加载网络图片
            
            
            



        

        

  • 相关阅读:
    深入理解CSS中的margin负值
    深入理解CSS浮动
    深入理解CSS绝对定位
    深入理解display属性
    JAVA-初步认识-第四章-内存空间的划分&栈内存&堆内存
    JAVA-初步认识-第四章-数组-概述和定义
    JAVA-初步认识-第四章-重载练习
    JAVA-初步认识-第四章-重载
    JAVA-初步认识-第四章-函数-内存加载过程
    JAVA-初步认识-第一章-整体的认识
  • 原文地址:https://www.cnblogs.com/peterleee/p/9373781.html
Copyright © 2020-2023  润新知