Android Volley框架使用详解

来源:互联网 发布:钟鼎创投 知乎 编辑:程序博客网 时间:2024/03/29 02:54

简介

Volley是一个由Google官方推出的网络通信库,它使得Android进行网络请求时更加方便、快速、健壮,同时对网络图片加载也提供了良好的支持。

在此欢迎大家关注我的个人微信公众号AndroidSharer,分享软件开发相关技术包括Android、Java Web、HTML5以及产品研发干货,偶尔喝点鸡汤
这里写图片描述

volley使用

1、获取volley源码(需要翻墙访问)

<span style="font-size:14px;"><code class="hljs ruby has-numbering"><span class="hljs-variable">$ </span>git clone <span class="hljs-symbol">https:</span>/<span class="hljs-regexp">/android.googlesource.com/platform</span><span class="hljs-regexp">/frameworks/volley</span><span class="hljs-variable">$ </span>cd volley<span class="hljs-variable">$ </span>android update project -p<span class="hljs-variable">$ </span>ant jar</code></span>

将编译得到的jar包引入到我们的项目中;没有翻墙的同学可以通过网络搜索下载,也可以在此下载
http://download.csdn.net/detail/fenghai22/8472045

2、使用实例

使用Volley必须在AndroidManifest.xml中添加 android.permission.INTERNET权限,使用Volley时Google建议创建volley单例工具类


<span style="font-size:14px;"><code class="hljs java has-numbering"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">VolleySingleton</span> {</span>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> VolleySingleton volleySingleton;    <span class="hljs-keyword">private</span> RequestQueue mRequestQueue;    <span class="hljs-keyword">private</span> ImageLoader mImageLoader;    <span class="hljs-keyword">private</span> Context mContext;    <span class="hljs-keyword">public</span> <span class="hljs-title">VolleySingleton</span>(Context context) {        <span class="hljs-keyword">this</span>.mContext = context;        mRequestQueue = getRequestQueue();        mImageLoader = <span class="hljs-keyword">new</span> ImageLoader(mRequestQueue,        <span class="hljs-keyword">new</span> ImageLoader.ImageCache(){            <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> LruCache<String,Bitmap> cache = <span class="hljs-keyword">new</span> LruCache<String ,Bitmap>(<span class="hljs-number">20</span>);            <span class="hljs-annotation">@Override</span>            <span class="hljs-keyword">public</span> Bitmap <span class="hljs-title">getBitmap</span>(String url){                <span class="hljs-keyword">return</span> cache.get(url);            }            <span class="hljs-annotation">@Override</span>            <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">putBitmap</span>(String url,Bitmap bitmap){                cache.put(url,bitmap);            }        });    }    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">synchronized</span> VolleySingleton <span class="hljs-title">getVolleySingleton</span>(Context context){        <span class="hljs-keyword">if</span>(volleySingleton == <span class="hljs-keyword">null</span>){            volleySingleton = <span class="hljs-keyword">new</span> VolleySingleton(context);        }        <span class="hljs-keyword">return</span> volleySingleton;    }    <span class="hljs-keyword">public</span> RequestQueue <span class="hljs-title">getRequestQueue</span>(){        <span class="hljs-keyword">if</span>(mRequestQueue == <span class="hljs-keyword">null</span>){            mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());        }        <span class="hljs-keyword">return</span> mRequestQueue;    }    <span class="hljs-keyword">public</span> <T> <span class="hljs-keyword">void</span> <span class="hljs-title">addToRequestQueue</span>(Request<T> req){        getRequestQueue().add(req);    }    <span class="hljs-keyword">public</span> ImageLoader <span class="hljs-title">getImageLoader</span>() {        <span class="hljs-keyword">return</span> mImageLoader;    }}</code></span>

首先使用 Volley.newRequestQueue获取 RequestQueue对象

<span style="font-size:14px;"><code class="hljs avrasm has-numbering">RequestQueue mRequestQueue = VolleySingleton<span class="hljs-preprocessor">.getVolleySingleton</span>(this<span class="hljs-preprocessor">.getApplicationContext</span>())<span class="hljs-preprocessor">.getRequestQueue</span>()<span class="hljs-comment">;</span></code></span>

RequestQueue是请求队列对象,它可以缓存所有的HTTP网络请求,然后按照其内部算法并发的发送这些网络请求,它能够很好的支撑高并发请求,不要每个请求都创建RequestQueue对象,创建多个RequestQueue会耗费资源

发送StringRequest请求

<span style="font-size:14px;"><code class="hljs java has-numbering">StringRequest stringRequest = <span class="hljs-keyword">new</span> StringRequest(Request.Method.GET,<span class="hljs-string">"https://www.baidu.com"</span>,<span class="hljs-keyword">new</span> Listener<String>(){            <span class="hljs-annotation">@Override</span>            <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onResponse</span>(String s) {                <span class="hljs-comment">//打印请求返回结果</span>                Log.e(<span class="hljs-string">"volley"</span>,s);            }        },<span class="hljs-keyword">new</span> ErrorListener(){            <span class="hljs-annotation">@Override</span>            <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onErrorResponse</span>(VolleyError volleyError) {                Log.e(<span class="hljs-string">"volleyerror"</span>,<span class="hljs-string">"erro2"</span>);            }        });<span class="hljs-comment">//将StringRequest对象添加进RequestQueue请求队列中</span>   VolleySingleton.getVolleySingleton(<span class="hljs-keyword">this</span>.getApplicationContext()).addToRequestQueue(stringRequest);</code></span>

到此已经完成了StringRequest请求。StringRequest提供了两个构造方法

<span style="font-size:14px;"><code class="hljs avrasm has-numbering">public StringRequest(java<span class="hljs-preprocessor">.lang</span><span class="hljs-preprocessor">.String</span> url, <span class="hljs-keyword">com</span><span class="hljs-preprocessor">.android</span><span class="hljs-preprocessor">.volley</span><span class="hljs-preprocessor">.Response</span><span class="hljs-preprocessor">.Listener</span><java<span class="hljs-preprocessor">.lang</span><span class="hljs-preprocessor">.String</span>> listener, <span class="hljs-keyword">com</span><span class="hljs-preprocessor">.android</span><span class="hljs-preprocessor">.volley</span><span class="hljs-preprocessor">.Response</span><span class="hljs-preprocessor">.ErrorListener</span> errorListener)<span class="hljs-comment">;</span>public StringRequest(int method, java<span class="hljs-preprocessor">.lang</span><span class="hljs-preprocessor">.String</span> url, <span class="hljs-keyword">com</span><span class="hljs-preprocessor">.android</span><span class="hljs-preprocessor">.volley</span><span class="hljs-preprocessor">.Response</span><span class="hljs-preprocessor">.Listener</span><java<span class="hljs-preprocessor">.lang</span><span class="hljs-preprocessor">.String</span>> listener, <span class="hljs-keyword">com</span><span class="hljs-preprocessor">.android</span><span class="hljs-preprocessor">.volley</span><span class="hljs-preprocessor">.Response</span><span class="hljs-preprocessor">.ErrorListener</span> errorListener)<span class="hljs-comment">;</span></code></span>

参数method是HTTP的请求类型,通常有GET和POST两种;参数url是请求地址;参数listener是服务器响应成功的回调,参数errorListener是服务器响应失败的回调。如果想通过POST方式请求并携带参数,遗憾的是StringRequest并没有提供带参数请求,但是当发送POST请求时,Volley会调用StringRequest的父类Request的getParams()方法来获取POST参数,所以我们只要使用StringRequest匿名类重写getParams()方法将参数传递进去就可以实现带参数的StringRequest请求。

<span style="font-size:14px;"><code class="hljs lasso has-numbering">StringRequest stringRequest <span class="hljs-subst">=</span> <span class="hljs-literal">new</span> StringRequest(Method<span class="hljs-built_in">.</span>POST, url,  listener, errorListener) {      @Override      <span class="hljs-keyword">protected</span> <span class="hljs-built_in">Map</span><span class="hljs-subst"><</span><span class="hljs-built_in">String</span>, <span class="hljs-built_in">String</span><span class="hljs-subst">></span> getParams() throws AuthFailureError {          <span class="hljs-built_in">Map</span><span class="hljs-subst"><</span><span class="hljs-built_in">String</span>, <span class="hljs-built_in">String</span><span class="hljs-subst">></span> <span class="hljs-built_in">map</span> <span class="hljs-subst">=</span> <span class="hljs-literal">new</span> HashMap<span class="hljs-subst"><</span><span class="hljs-built_in">String</span>, <span class="hljs-built_in">String</span><span class="hljs-subst">></span>();          <span class="hljs-built_in">map</span><span class="hljs-built_in">.</span>put(<span class="hljs-string">"params1"</span>, <span class="hljs-string">"value1"</span>);          <span class="hljs-built_in">map</span><span class="hljs-built_in">.</span>put(<span class="hljs-string">"params2"</span>, <span class="hljs-string">"value2"</span>);          <span class="hljs-keyword">return</span> <span class="hljs-built_in">map</span>;      }  }; </code></span>

发送JsonObjectRequest请求

<span style="font-size:14px;"><code class="hljs java has-numbering">JsonObjectRequest jr = <span class="hljs-keyword">new</span> JsonObjectRequest(Request.Method.GET,url,<span class="hljs-keyword">null</span>,<span class="hljs-keyword">new</span> Response.Listener<JSONObject>(){            <span class="hljs-annotation">@Override</span>            <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onResponse</span>(JSONObject jsonObject) {                Log.e(<span class="hljs-string">"volley"</span>,jsonObject.toString());            }        },<span class="hljs-keyword">new</span> ErrorListener(){            <span class="hljs-annotation">@Override</span>            <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onErrorResponse</span>(VolleyError volleyError) {                Log.e(<span class="hljs-string">"volleyerror"</span>,<span class="hljs-string">"erro"</span>);            }        }); VolleySingleton.getVolleySingleton(<span class="hljs-keyword">this</span>.getApplicationContext()).addToRequestQueue(jr);</code></span>

JsonObjectRequest的构造方法参数和StringRequest一致,不在此累赘。

使用ImageRequest加载图片

<span style="font-size:14px;"><code class="hljs java has-numbering">ImageView mImageView;String url = <span class="hljs-string">"http://i.imgur.com/7spzG.png"</span>;mImageView = (ImageView) findViewById(R.id.myImage);ImageRequest request = <span class="hljs-keyword">new</span> ImageRequest(url,    <span class="hljs-keyword">new</span> Response.Listener<Bitmap>() {        <span class="hljs-annotation">@Override</span>        <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onResponse</span>(Bitmap bitmap) {            mImageView.setImageBitmap(bitmap);        }    }, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, Config.RGB_565,    <span class="hljs-keyword">new</span> Response.ErrorListener() {        <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onErrorResponse</span>(VolleyError error) {            mImageView.setImageResource(R.drawable.image_load_error);        }    });    VolleySingleton.getVolleySingleton(<span class="hljs-keyword">this</span>.getApplicationContext()).addToRequestQueue(request);</code></span>

ImageRequest的构造函数

<span style="font-size:14px;"><code class="hljs avrasm has-numbering">public ImageRequest(java<span class="hljs-preprocessor">.lang</span><span class="hljs-preprocessor">.String</span> url, <span class="hljs-keyword">com</span><span class="hljs-preprocessor">.android</span><span class="hljs-preprocessor">.volley</span><span class="hljs-preprocessor">.Response</span><span class="hljs-preprocessor">.Listener</span><android<span class="hljs-preprocessor">.graphics</span><span class="hljs-preprocessor">.Bitmap</span>> listener, int maxWidth, int maxHeight, android<span class="hljs-preprocessor">.graphics</span><span class="hljs-preprocessor">.Bitmap</span><span class="hljs-preprocessor">.Config</span> decodeConfig, <span class="hljs-keyword">com</span><span class="hljs-preprocessor">.android</span><span class="hljs-preprocessor">.volley</span><span class="hljs-preprocessor">.Response</span><span class="hljs-preprocessor">.ErrorListener</span> errorListener) { <span class="hljs-comment">/* compiled code */</span> }</code></span><ul style="display: block;" class="pre-numbering"><li><span style="font-size:14px;">1</span></li></ul>

参数url是图片地址,参数listener是请求响应成功回调,参数maxWidth是图片最大宽度,参数maxHeight是图片最大高度,如果指定的网络图片的宽度或高度大于这里的最大值,则会对图片进行压缩,指定成0的话就表示不管图片有多大,都不会进行压缩。参数decodeConfig是图片的颜色属性,其值是Bitmap.Config类的几个常量,参数errorListener是请求响应失败回调

使用 ImageLoader 加载图片

<span style="font-size:14px;"><code class="hljs avrasm has-numbering">ImageLoader mImageLoader<span class="hljs-comment">;</span>ImageView mImageView<span class="hljs-comment">;</span>private static final String IMAGE_URL =    <span class="hljs-string">"http://developer.android.com/images/training/system-ui.png"</span><span class="hljs-comment">;</span>mImageView = (ImageView) findViewById(R<span class="hljs-preprocessor">.id</span><span class="hljs-preprocessor">.regularImageView</span>)<span class="hljs-comment">;</span>mImageLoader = VolleySingleton<span class="hljs-preprocessor">.getVolleySingleton</span>(this<span class="hljs-preprocessor">.getApplicationContext</span>())<span class="hljs-preprocessor">.getImageLoader</span>()<span class="hljs-comment">;</span>//IMAGE_URL是图片网络地址//mImageView是ImageView实例//R<span class="hljs-preprocessor">.drawable</span><span class="hljs-preprocessor">.def</span>_image默认图片id//R<span class="hljs-preprocessor">.drawable</span><span class="hljs-preprocessor">.err</span>_image加载图片错误时的图片mImageLoader<span class="hljs-preprocessor">.get</span>(IMAGE_URL, ImageLoader<span class="hljs-preprocessor">.getImageListener</span>(mImageView,         R<span class="hljs-preprocessor">.drawable</span><span class="hljs-preprocessor">.def</span>_image, R<span class="hljs-preprocessor">.drawable</span><span class="hljs-preprocessor">.err</span>_image))<span class="hljs-comment">;</span></code></span>

使用NetworkImageView加载图片

XML布局文件

<span style="font-size:14px;"><code class="hljs avrasm has-numbering"><<span class="hljs-keyword">com</span><span class="hljs-preprocessor">.android</span><span class="hljs-preprocessor">.volley</span><span class="hljs-preprocessor">.toolbox</span><span class="hljs-preprocessor">.NetworkImageView</span>        android:id=<span class="hljs-string">"@+id/networkImageView"</span>        android:layout_width=<span class="hljs-string">"150dp"</span>        android:layout_height=<span class="hljs-string">"170dp"</span>        android:layout_centerHorizontal=<span class="hljs-string">"true"</span> /></code></span>
<span style="font-size:14px;"><code class="hljs avrasm has-numbering">ImageLoader mImageLoader<span class="hljs-comment">;</span>NetworkImageView mNetworkImageView<span class="hljs-comment">;</span>private static final String IMAGE_URL =    <span class="hljs-string">"http://developer.android.com/images/training/system-ui.png"</span><span class="hljs-comment">;</span>mNetworkImageView = (NetworkImageView) findViewById(R<span class="hljs-preprocessor">.id</span><span class="hljs-preprocessor">.networkImageView</span>)<span class="hljs-comment">;</span>mImageLoader = VolleySingleton<span class="hljs-preprocessor">.getVolleySingleton</span>(this<span class="hljs-preprocessor">.getApplicationContext</span>())<span class="hljs-preprocessor">.getImageLoader</span>()<span class="hljs-comment">;</span>mNetworkImageView<span class="hljs-preprocessor">.setImageUrl</span>(IMAGE_URL, mImageLoader)<span class="hljs-comment">;</span></code></span>

我们可以调用它的setDefaultImageResId()方法、setErrorImageResId()方法和setImageUrl()方法来分别设置加载中显示的图片,加载失败时显示的图片

取消网络请求

Volley还提供了取消网络请求的方法并且可以联动Activity的生命周期,比如在Activity的onStop()方法中调用cance()方法取消网络请求。

<span style="font-size:14px;"><code class="hljs java has-numbering"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> String TAG = <span class="hljs-string">"MyTag"</span>;StringRequest stringRequest; <span class="hljs-comment">// Assume this exists.</span>RequestQueue mRequestQueue;  <span class="hljs-comment">// Assume this exists.</span><span class="hljs-comment">// Set the tag on the request.</span>stringRequest.setTag(TAG);<span class="hljs-comment">// Add the request to the RequestQueue.</span>mRequestQueue.add(stringRequest);</code></span>

Activity的onStop()方法

<span style="font-size:14px;"><code class="hljs java has-numbering"><span class="hljs-annotation">@Override</span><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onStop</span> () {    <span class="hljs-keyword">super</span>.onStop();    <span class="hljs-keyword">if</span> (mRequestQueue != <span class="hljs-keyword">null</span>) {        mRequestQueue.cancelAll(TAG);    }}</code></span>

0 0