关于Volly框架使用的心得(1)

一、在这里先对 Volly 做一个简单的了解

jar包下载的地址:http://download.csdn.net/detail/sinyu890807/7152015 。下载后放置到libs中添加依赖


我们平时在开发Android应用的时候不可避免地都需要用到网络技术,而多数情况下应用程序都会使用HTTP协议来发送和接收网络数据。android系统中主要提供了两种方式来进行HTTP通信,HttpURLConnection和HttpClient,几乎在任何项目的代码中我们都能看到这两个类的身影,使用率非常高。


不过HttpURLConnection和HttpClient的用法还是稍微有些复杂的,如果不进行适当封装的话,很容易就会写出不少重复代码。于是乎,一些Android网络通信框架也就应运而生,比如说AsyncHttpClient,它把HTTP所有的通信细节全部封装在了内部,我们只需要简单调用几行代码就可以完成通信操作了。再比如Universal-Image-Loader,它使得在界面上显示网络图片的操作变得极度简单,开发者不用关心如何从网络上获取图片,也不用关心开启线程、回收图片资源等细节,Universal-Image-Loader已经把一切都做好了。


Android开发团队也是意识到了有必要将HTTP的通信操作再进行简单化,于是在2013年Google I/O大会上推出了一个新的网络通信框架——Volley。Volley可是说是把AsyncHttpClient和Universal-Image-Loader的优点集于了一身,既可以像AsyncHttpClient一样非常简单地进行HTTP通信,也可以像Universal-Image-Loader一样轻松加载网络上的图片。除了简单易用之外,Volley在性能方面也进行了大幅度的调整,它的设计目标就是非常适合去进行数据量不大,但通信频繁的网络操作,而对于大数据量的网络操作,比如说下载文件等,Volley的表现就会非常糟糕。


Volley的简单用法

主要有三个步骤:

1. 创建一个RequestQueue对象。

2. 创建一个StringRequest对象。

3. 将StringRequest对象添加到RequestQueue里面

StringRequest stringRequest = new StringRequest(Method.POST, url,  listener, errorListener);  


使用volley前,首先要建立一个volley的全局请求队列,用来管理请求。

在Application类中创建全局请求队列,在onCreate()方法中实例化请求队列,为请求队列设置get方法。

public class MyApplication extends Application {
    //Volley的全局请求队列
    public static RequestQueue sRequestQueue;

    /**
     * @return Volley全局请求队列
     */
    public static RequestQueue getRequestQueue() {
        return sRequestQueue;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        //实例化Volley全局请求队列
        sRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

然后要在AndroidManifest中注册Application,添加网络权限。

<uses-permission android:name="android.permission.INTERNET"/>
<application android:name=".MyApplication"/>
 
 
  • 1
  • 2
  • 1
  • 2

StringRequest和JsonObjectRequest

可以在volley源码中查看volley有哪些请求方式,这里以StringRequest和JsonObjectRequest为例。

JsonObjectRequest处理返回JSON格式数据的请求,当返回数据格式非JSON格式或对所请求的数据的返回格式不确定时使用StringRequest。

下面只写出部分示例代码,完整代码请看

https://github.com/VDerGoW/AndroidMain/tree/master/volley-demo/src/main/java/tips/volleytest

StringRequest的使用示例:

  1. 创建StringRequest实例,传入请求类型(GET/POST)请求的URL,请求成功的监听器,请求失败的监听器四个参数。其中两个监听器需要实现接口方法,分别处理请求成功和请求失败的事件。

  2. 为StringRequest实例设置tag,可以通过该tag在全局队列中访问到该实例。

  3. 将StringRequest实例加入到全局队列中。

GET方式:

/**
 * Volley的StringRequest使用示例
 * HTTP method : GET
 */
public void volleyStringRequestDemo_GET() {

    //Volley request,参数:请求方式,请求的URL,请求成功的回调,请求失败的回调
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url_GET, new Response.Listener<String>() {
        /**
         * 请求成功的回调
         * @param response 请求返回的数据
         */
        @Override
        public void onResponse(String response) {
            // TODO: 处理返回结果
            Log.i("### onResponse", "GET_StringRequest:" + response);
        }
    }, new Response.ErrorListener() {
        /**
         * 请求失败的回调
         * @param error VolleyError
         */
        @Override
        public void onErrorResponse(VolleyError error) {
            // TODO: 处理错误
            Log.e("### onErrorResponse", "GET_StringRequest:" + error.toString());
        }
    });

    //为request设置tag,通过该tag在全局队列中访问request
    stringRequest.setTag(VOLLEY_TAG);//StringRequestTest_GET

    //将request加入全局队列
    MyApplication.getRequestQueue().add(stringRequest);
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

POST方式的使用示例:

使用POST方式需要实现StringRequest类的getParams()方法,实现参数映射。

/**
 * Volley的StringRequest使用示例
 * HTTP method : POST
 * 内部注释和方法volleyStringRequestDemo_GET()相同
 */
public void volleyStringRequestDome_POST() {

    String url = JUHE_API_URL;

    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            // TODO: 处理返回结果
            Log.i("### onResponse", "POST_StringRequest:" + response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // TODO: 处理错误
            Log.e("### onErrorResponse", "POST_StringRequest:" + error.toString());
        }
    }) {
        /**
         * 返回含有POST或PUT请求的参数的Map
         */
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {

            Map<String, String> paramMap = new HashMap<>();
            // TODO: 处理POST参数
            paramMap.put("postcode", postcode);
            paramMap.put("key", JUHE_APPKEY);

            return paramMap;
        }
    };

    stringRequest.setTag(VOLLEY_TAG);//StringRequest_POST

    MyApplication.getRequestQueue().add(stringRequest);
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

JsonObjectRequest的使用示例:

GET方式:

/**
 * Volley的JsonObjectRequest使用示例
 * HTTP method : GET
 * 内部注释和方法volleyStringRequestDemo_GET()相同
 */
public void volleyJsonObjectRequestDemo_GET() {

    /*
    * 第三个参数:request的参数(POST),传入null表示没有需要传递的参数
    * 此处为GET方式传输,参数已经包含在URL中
    * */
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url_GET, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            // TODO: 处理返回结果
            Log.i("### onResponse", "GET_JsonObjectRequest:" + response.toString());
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // TODO: 处理错误
            Log.e("### onErrorResponse", "GET_JsonObjectRequest:" + error.toString());
        }
    });

    jsonObjectRequest.setTag(VOLLEY_TAG);//JsonObjectRequestTest_GET

    MyApplication.getRequestQueue().add(jsonObjectRequest);
}

ImageRequest的使用

ImageRequest的使用示例:

public class VolleyImageRequestDemo {

    public static final String IMAGE_URL = "https://www.baidu.com/img/bd_logo1.png";
    public static final String VOLLEY_TAG = "tag_volley_image_request";

    public void volleyImageRequestDemo(final Callback callback) {

        // @param maxWidth : Maximum width to decode this bitmap to, or zero for none
        // @param maxHeight : Maximum height to decode this bitmap to, or zero for none
        // If both width and height are zero, the image will be decoded to its natural size
        ImageRequest imageRequest = new ImageRequest(IMAGE_URL, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap response) {
                // 请求成功

                callback.onSuccess(response);
            }
        }, 0, 0, ImageView.ScaleType.FIT_XY, Bitmap.Config.RGB_565, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // 请求失败

                Log.i("### onErrorResponse", "ImageRequest:" + error.toString());
                callback.onError(error);
            }
        });

        imageRequest.setTag(VOLLEY_TAG);

        MyApplication.getRequestQueue().add(imageRequest);
    }

    // 为了能单独写一个类出来,又能把请求到的图片设置到Activity的ImageView中
    // 我写了个回调接口,如果把ImageRequest直接写在Activity中,就不需要回调了
    public interface Callback {
        void onSuccess(Bitmap response);

        void onError(VolleyError error);
    }
}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

ImageLoader的使用

使用ImageLoader,首先要有一个ImageCache,所以要定义一个类,实现ImageLoader.ImageCache接口。然后实现getBitmap()方法和putBitmap()方法,并在构造方法中实例化一个LruCache对象,用于存放图片。

ImageCache示例:

/**
 * Simple cache adapter interface. If provided to the ImageLoader, it
 * will be used as an L1 cache before dispatch to Volley. Implementations
 * must not block. Implementation with an LruCache is recommended.
 */
public class VolleyBitmapCacheDemo implements ImageLoader.ImageCache {

    private LruCache<String, Bitmap> mCache;

    public VolleyBitmapCacheDemo() {
        int maxMemorySize = 1024 * 1024 * 10;
        mCache = new LruCache<String, Bitmap>(maxMemorySize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return bitmap.getRowBytes() * bitmap.getHeight();
            }
        };
    }

    @Override
    public Bitmap getBitmap(String key) {
        return mCache.get(key);
    }

    @Override
    public void putBitmap(String key, Bitmap bitmap) {
        mCache.put(key, bitmap);
    }
}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

然后在Activity中使用ImageLoader:

ImageLoader imageLoader = new ImageLoader(MyApplication.getRequestQueue(), new VolleyBitmapCacheDemo());
ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(mLoaderImage, R.mipmap.ic_launcher,R.mipmap.ic_launcher);
imageLoader.get(IMAGE_URL, imageListener);
  
  
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值