Android Volley的简单使用

volley 

  项目地址 https://github.com/smanikandan14/Volley-demo

  • JSON,图像等的异步下载;
  • 网络请求的排序(scheduling)
  • 网络请求的优先级处理
  • 缓存
  • 多级别取消请求
  • 和Activity和生命周期的联动(Activity结束时同时取消所有网络请求)

使用Volley开源库时,使用下载 volley.jar,然后导入到Android项目(简单来说就是将volley.jar复制到Android项目中的libs目录)

1、使用Volley实现JSON字符串请求

通过使用 Volley 实现 JSON 字符串请求,通过极少的代码以及更方便理解的参数完成通信。

getJSONVolley()

    //获取json字符串  
        public void getJSONVolley() {  
            //获取Volley的请求对象  
            RequestQueue requestQueue = Volley.newRequestQueue(this);  
            //请求地址  
            //String JSONDataUrl = "http://www.wwtliu.com/jsondata.html";//该地址过期  
            //自己编写php文件,放在ip为121.42.204.31的服务器上  
            String JSONDataUrl = "http://121.42.204.31/MyTest/myvolley.php";  
            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, JSONDataUrl, null,   
                    new Response.Listener<JSONObject>() {  
                        @Override  
                        public void onResponse(JSONObject response) {  
                            // TODO Auto-generated method stub  
                            System.out.println("response="+response);  
                        }  
                    }, new Response.ErrorListener() {  
                        @Override  
                        public void onErrorResponse(VolleyError error) {  
                            // TODO Auto-generated method stub  
                            System.out.println("对不起,有问题");  
                        }  
                    });   
            requestQueue.add(jsonObjectRequest);  
        }  

 

2、使用Volley实现异步加载图片

通过使用 Volley 实现图片的异步加载,要比使用传统的通信方式方便很多。

    public void loadImageVolley() {  
            String imageurl = "http://(修改为服务器ip,后面为访问的图片)/MyTest/93.jpg";  
            RequestQueue requestQueue = Volley.newRequestQueue(this);  
            //缓存操作  
            final LruCache<String, Bitmap> lrucache = new LruCache<String, Bitmap>(20);  
            ImageCache imageCache = new ImageCache() {  
                @Override  
                public void putBitmap(String key, Bitmap value) {  
                    // TODO Auto-generated method stub  
                    lrucache.put(key, value);  
                }  
                  
                @Override  
                public Bitmap getBitmap(String key) {  
                    // TODO Auto-generated method stub  
                    return lrucache.get(key);  
                }  
            };  
              
            ImageLoader imageLoader = new ImageLoader(requestQueue, imageCache);  
            ImageListener listener = imageLoader.getImageListener(iv1, R.drawable.ic_launcher, R.drawable.ic_launcher);  
            imageLoader.get(imageurl, listener);  
        }  

 

其中iv1是ImageView组件,放置在布局文件中。

3、使用NetWorkImageView完成图片加载

通过使用 Volley 提供的 NetWorkImageView 完成图片的加载,对比异步加载图片的优点。

    public void NetWorkImageViewVolley() {  
            String imageUrl = "http://121.42.204.31/MyTest/93.jpg";  
            //创建请求对象  
            RequestQueue requestQueue = Volley.newRequestQueue(this);  
            final LruCache<String, Bitmap> lruCache = new LruCache<String, Bitmap>(20);  
            //图像缓存  
            ImageCache imageCache = new ImageCache() {  
      
                @Override  
                public void putBitmap(String key, Bitmap value) {  
                    // TODO Auto-generated method stub  
                    lruCache.put(key, value);  
                }  
                  
                @Override  
                public Bitmap getBitmap(String key) {  
                    // TODO Auto-generated method stub  
                    return lruCache.get(key);  
                }  
            };  
            ImageLoader imageLoader = new ImageLoader(requestQueue, imageCache);  
            iv2.setTag("url");  
            iv2.setImageUrl(imageUrl, imageLoader);  
        }  

 

其中iv2是NetWorkImageView组件,放置在布局文件中。

完整的Android程序(其中 服务器ip需要进行修改):

布局文件

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
        xmlns:tools="http://schemas.android.com/tools"  
        android:layout_width="match_parent"  
        android:layout_height="match_parent"  
        android:paddingBottom="@dimen/activity_vertical_margin"  
        android:paddingLeft="@dimen/activity_horizontal_margin"  
        android:paddingRight="@dimen/activity_horizontal_margin"  
        android:paddingTop="@dimen/activity_vertical_margin"  
        tools:context="com.jikexueyuan.myvolley.MainActivity" >  
      
        <ImageView  
            android:id="@+id/iv1"  
            android:layout_width="100dp"  
            android:layout_height="100dp"/>  
      
        <com.android.volley.toolbox.NetworkImageView  
            android:id="@+id/iv2"  
            android:layout_width="100dp"  
            android:layout_height="100dp"  
            android:layout_below="@id/iv1"  
            android:layout_toRightOf="@id/iv1"  
            android:src="@drawable/ic_launcher"/>  
    </RelativeLayout>  


MainActivity.java

    package com.example.myvolley;  
      
    import org.json.JSONObject;  
      
    import android.graphics.Bitmap;  
    import android.os.Bundle;  
    import android.support.v4.util.LruCache;  
    import android.support.v7.app.ActionBarActivity;  
    import android.widget.ImageView;  
      
    import com.android.volley.Request;  
    import com.android.volley.RequestQueue;  
    import com.android.volley.Response;  
    import com.android.volley.VolleyError;  
    import com.android.volley.toolbox.ImageLoader;  
    import com.android.volley.toolbox.ImageLoader.ImageCache;  
    import com.android.volley.toolbox.ImageLoader.ImageListener;  
    import com.android.volley.toolbox.JsonObjectRequest;  
    import com.android.volley.toolbox.NetworkImageView;  
    import com.android.volley.toolbox.Volley;  
      
    /* 
     * Volley是Android平台网络通信库:更快。更简单。更健壮。(适用数据不大,通信频繁的情况) 
     * Volley提供的功能: 
     * 1、JSON、图片(比不) 
     * 2、网络请求的排序 
     * 3、网络请求的优先级处理 
     * 4、缓存 
     * 5、多级别的取消请求 
     * 6、与Activity生命周期联动 
     *  
     * 获取Volley 
     * git clone https://android.googlesource.com/platform/frameworks/volley 
     *  
     */  
    public class MainActivity extends ActionBarActivity {  
        private ImageView iv1;  
        private NetworkImageView iv2;  
          
        @Override  
        protected void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.activity_main);  
            getJSONVolley();  
              
            init();  
        }  
          
        public void init() {  
            iv1 = (ImageView)findViewById(R.id.iv1);  
            iv2 = (NetworkImageView)findViewById(R.id.iv2);  
            loadImageVolley();  
            NetWorkImageViewVolley();  
        }  
      
        //获取json字符串  
        public void getJSONVolley() {  
            //获取Volley的请求对象  
            RequestQueue requestQueue = Volley.newRequestQueue(this);  
            //请求地址  
            //自己编写php文件,放在服务器上  
            String JSONDataUrl = "http://(修改为服务器ip)/MyTest/myvolley.php";  
            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, JSONDataUrl, null,   
                    new Response.Listener<JSONObject>() {  
                        @Override  
                        public void onResponse(JSONObject response) {  
                            // TODO Auto-generated method stub  
                            System.out.println("response="+response);  
                        }  
                    }, new Response.ErrorListener() {  
                        @Override  
                        public void onErrorResponse(VolleyError error) {  
                            // TODO Auto-generated method stub  
                            System.out.println("出现问题");  
                        }  
                    });   
            requestQueue.add(jsonObjectRequest);  
        }  
          
        public void loadImageVolley() {  
            String imageurl = "http://<span style="font-family: Arial, Helvetica, sans-serif;">(修改为服务器ip)</span>/MyTest/93.jpg";  
            RequestQueue requestQueue = Volley.newRequestQueue(this);  
            //缓存操作  
            final LruCache<String, Bitmap> lrucache = new LruCache<String, Bitmap>(20);  
            ImageCache imageCache = new ImageCache() {  
                @Override  
                public void putBitmap(String key, Bitmap value) {  
                    // TODO Auto-generated method stub  
                    lrucache.put(key, value);  
                }  
                  
                @Override  
                public Bitmap getBitmap(String key) {  
                    // TODO Auto-generated method stub  
                    return lrucache.get(key);  
                }  
            };  
              
            ImageLoader imageLoader = new ImageLoader(requestQueue, imageCache);  
            ImageListener listener = imageLoader.getImageListener(iv1, R.drawable.ic_launcher, R.drawable.ic_launcher);  
            imageLoader.get(imageurl, listener);  
        }  
          
        public void NetWorkImageViewVolley() {  
            String imageUrl = "http://<span style="font-family: Arial, Helvetica, sans-serif;">(修改为服务器ip)</span>/MyTest/93.jpg";  
            //创建请求对象  
            RequestQueue requestQueue = Volley.newRequestQueue(this);  
            final LruCache<String, Bitmap> lruCache = new LruCache<String, Bitmap>(20);  
            //图像缓存  
            ImageCache imageCache = new ImageCache() {  
      
                @Override  
                public void putBitmap(String key, Bitmap value) {  
                    // TODO Auto-generated method stub  
                    lruCache.put(key, value);  
                }  
                  
                @Override  
                public Bitmap getBitmap(String key) {  
                    // TODO Auto-generated method stub  
                    return lruCache.get(key);  
                }  
            };  
            ImageLoader imageLoader = new ImageLoader(requestQueue, imageCache);  
            iv2.setTag("url");  
            iv2.setImageUrl(imageUrl, imageLoader);  
        }  
    }  


AndroidManifest.xml配置文件中需添加internet权限。

上述所用到的服务器端PHP文件

myvolley.php

    <?php  
        $arr=array();  
        $arr['name']="dreamboy";  
        $arr['age']=18;  
        $arr['sex']="男";  
        echo json_encode($arr);  
    ?>  


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值