TOP

Volley框架

Volley框架

volley是谷歌官方在2013年推出的Android平台上的网络通信库

特点

  • 网络通信更快,更简单,开发效率高,稳定性高。
  • 对get和post网络请求以及网络图片高效的异步处理请求。
  • 可以对网络请求进行优先级排序处理
  • 网络请求的缓存
  • 多级别取消请求。
  • 和Activity生命周期的联动。

缺点
不适合数据的上传与下载


Get和Post请求接口的使用
请求对象

  • StringRequest 返回结果类型不确定(它包含后面两种)
  1. StringRequest request =newStringRequest(Request.Method.GET, REQUEST_URL,newResponse.Listener<String>(){
  2. @Override
  3. publicvoid onResponse(String s){//数据请求成功
  4. result.setText("请求成功:"+ s);
  5. }
  6. },newResponse.ErrorListener(){
  7. @Override
  8. publicvoid onErrorResponse(VolleyError volleyError){//数据请求失败
  9. result.setText("请求失败:"+ volleyError.getMessage());
  10. }
  11. });
  • JsonObjectRequest
  1. JSONObject jsonRequest =newJSONObject();//Get请求传递参数jsonRequest可以为空null
  2. JsonObjectRequest request =newJsonObjectRequest(Request.Method.GET, REQUEST_URL,null,newResponse.Listener<JSONObject>(){
  3. @Override
  4. publicvoid onResponse(JSONObject jsonObject){
  5. result.setText("请求成功:"+ jsonObject);
  6. }
  7. },newResponse.ErrorListener(){
  8. @Override
  9. publicvoid onErrorResponse(VolleyError volleyError){
  10. result.setText("请求失败:"+ volleyError.getMessage());
  11. }
  12. });
  • JsonArrayRequest
  1. JsonArrayRequest request =newJsonArrayRequest(REQUEST_URL,newResponse.Listener<JSONArray>(){
  2. @Override
  3. publicvoid onResponse(JSONArray jsonArray){
  4. result.setText("请求成功:"+ jsonArray);
  5. }
  6. },newResponse.ErrorListener(){
  7. @Override
  8. publicvoid onErrorResponse(VolleyError volleyError){
  9. result.setText("请求失败:"+ volleyError.getMessage());
  10. }
  11. });

网络请求队列建立和取消队列建立

  • 建立一个全局的请求队列。
  1. //创建请求队列
  2. privatestaticRequestQueue queues;
  3. //初始化请求队列
  4. queues =Volley.newRequestQueue(getApplicationContext());
  • 建立一个请求并加入队列中。
  1. MyApplication.getQueues().add(request);
  • 取消队列
  1. MyApplication.getQueues().cancelAll(tag);

与Activity生命周期的联动

  • 可以在Activity销毁的同时关闭请求。
  • 设置Tag标签,在onStop()里执行取消请求。
  1. @Override
  2. protectedvoid onStop(){
  3. super.onStop();
  4. //结束请求
  5. MyApplication.getQueues().cancelAll("StringRequest_get");
  6. }

Volley调用实例源码展示

demo效果如下
Volley

  • 布局文件
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:id="@+id/activity_main"
  6. android:layout_width="match_parent"
  7. android:layout_height="match_parent"
  8. android:orientation="vertical"
  9. tools:context="com.xhb.app.MainActivity"
  10. >
  11. <ScrollView
  12. android:layout_width="match_parent"
  13. android:layout_height="match_parent">
  14. <LinearLayout
  15. android:layout_width="match_parent"
  16. android:layout_height="match_parent"
  17. android:orientation="vertical">
  18. <RelativeLayout
  19. android:layout_width="match_parent"
  20. android:layout_height="wrap_content"
  21. android:gravity="center">
  22. <Button
  23. android:id="@+id/_StringRequestGet"
  24. android:layout_width="wrap_content"
  25. android:layout_height="wrap_content"
  26. android:onClick="StringRequestGet"
  27. android:text="StringRequestGet"
  28. android:textAllCaps="false"/>
  29. <Button
  30. android:id="@+id/StringRequestPost"
  31. android:layout_width="wrap_content"
  32. android:layout_height="wrap_content"
  33. android:layout_marginLeft="20dp"
  34. android:layout_toRightOf="@id/_StringRequestGet"
  35. android:onClick="StringRequestPost"
  36. android:text="StringRequestPost"
  37. android:textAllCaps="false"/>
  38. </RelativeLayout>
  39. <RelativeLayout
  40. android:layout_width="match_parent"
  41. android:layout_height="wrap_content"
  42. android:gravity="center">
  43. <Button
  44. android:id="@+id/JsonObjectRequestGet"
  45. android:layout_width="wrap_content"
  46. android:layout_height="wrap_content"
  47. android:onClick="JsonObjectRequestGet"
  48. android:text="JsonObjectRequestGet"
  49. android:textAllCaps="false"/>
  50. <Button
  51. android:id="@+id/JsonObjectRequestPost"
  52. android:layout_width="wrap_content"
  53. android:layout_height="wrap_content"
  54. android:layout_marginLeft="20dp"
  55. android:layout_toRightOf="@id/JsonObjectRequestGet"
  56. android:onClick="JsonObjectRequestPost"
  57. android:text="JsonObjectRequestPost"
  58. android:textAllCaps="false"/>
  59. </RelativeLayout>
  60. <RelativeLayout
  61. android:layout_width="match_parent"
  62. android:layout_height="wrap_content"
  63. android:gravity="center">
  64. <Button
  65. android:id="@+id/JsonArrayRequest"
  66. android:layout_width="wrap_content"
  67. android:layout_height="wrap_content"
  68. android:layout_alignParentLeft="true"
  69. android:layout_alignParentStart="true"
  70. android:layout_alignParentTop="true"
  71. android:onClick="JsonArrayRequest"
  72. android:text="JsonArrayRequest"
  73. android:textAllCaps="false"/>
  74. </RelativeLayout>
  75. <RelativeLayout
  76. android:layout_width="match_parent"
  77. android:layout_height="wrap_content"
  78. android:gravity="center">
  79. <Button
  80. android:id="@+id/MyRequestGet"
  81. android:layout_width="wrap_content"
  82. android:layout_height="wrap_content"
  83. android:onClick="MyRequestGet"
  84. android:text="MyRequestGet"
  85. android:textAllCaps="false"/>
  86. <Button
  87. android:id="@+id/MyRequestPost"
  88. android:layout_width="wrap_content"
  89. android:layout_height="wrap_content"
  90. android:layout_marginLeft="20dp"
  91. android:layout_toRightOf="@id/MyRequestGet"
  92. android:onClick="MyRequestPost"
  93. android:text="MyRequestPost"
  94. android:textAllCaps="false"/>
  95. </RelativeLayout>
  96. <RelativeLayout
  97. android:layout_width="match_parent"
  98. android:layout_height="wrap_content"
  99. android:gravity="center">
  100. <Button
  101. android:id="@+id/ImageRequest"
  102. android:layout_width="wrap_content"
  103. android:layout_height="wrap_content"
  104. android:onClick="ImageRequest"
  105. android:text="ImageRequest"
  106. android:textAllCaps="false"/>
  107. <Button
  108. android:id="@+id/ImageLoader"
  109. android:layout_width="wrap_content"
  110. android:layout_height="wrap_content"
  111. android:layout_marginLeft="20dp"
  112. android:layout_toRightOf="@id/ImageRequest"
  113. android:onClick="ImageLoader"
  114. android:text="ImageLoader"
  115. android:textAllCaps="false"/>
  116. </RelativeLayout>
  117. <RelativeLayout
  118. android:layout_width="match_parent"
  119. android:layout_height="wrap_content"
  120. android:gravity="center">
  121. <ImageView
  122. android:id="@+id/image_imageRequest"
  123. android:layout_width="100dp"
  124. android:layout_height="100dp"
  125. android:src="@mipmap/ic_launcher"
  126. android:textAllCaps="false"/>
  127. <ImageView
  128. android:id="@+id/image_iamgeLoader"
  129. android:layout_width="100dp"
  130. android:layout_height="100dp"
  131. android:layout_marginLeft="20dp"
  132. android:layout_toRightOf="@id/image_imageRequest"
  133. android:src="@mipmap/ic_launcher"
  134. android:textAllCaps="false"/>
  135. </RelativeLayout>
  136. <TextView
  137. android:layout_width="match_parent"
  138. android:layout_height="wrap_content"
  139. android:layout_marginTop="20dp"
  140. android:text="请求结果为:"/>
  141. <TextView
  142. android:id="@+id/result"
  143. android:layout_width="match_parent"
  144. android:layout_height="0dp"
  145. android:layout_weight="1"/>
  146. </LinearLayout>
  147. </ScrollView>
  148. </LinearLayout>
  • 全局初始化文件
  1. publicclassMyApplicationextendsApplication{
  2. //创建请求队列
  3. privatestaticRequestQueue queues;
  4. @Override
  5. publicvoid onCreate(){
  6. super.onCreate();
  7. //初始书请求队列
  8. queues =Volley.newRequestQueue(getApplicationContext());
  9. }
  10. publicstaticRequestQueue getQueues(){
  11. return queues;
  12. }
  13. }
  • 主要实现文件
  1. publicclassMainActivityextendsAppCompatActivity{
  2. publicstaticfinalString BASE ="http://op.juhe.cn/onebox/weather/query";
  3. publicstaticfinalString REQUEST_URL = BASE +"?cityname=%E5%8D%81%E5%A0%B0&key=634f562a2b3900e051c6af6e2dc3017e";
  4. publicstaticfinalString IMAGE_URL ="https://pic.cnblogs.com/avatar/789527/20160825180355.png";
  5. privateTextView result;
  6. privateImageView image_imageRequest, image_iamgeLoader;
  7. @Override
  8. protectedvoid onCreate(Bundle savedInstanceState){
  9. super.onCreate(savedInstanceState);
  10. setContentView(R.layout.activity_main);
  11. result =(TextView) findViewById(R.id.result);
  12. image_imageRequest =(ImageView) findViewById(R.id.image_imageRequest);
  13. image_iamgeLoader =(ImageView) findViewById(R.id.image_iamgeLoader);
  14. }
  15. publicvoidStringRequestGet(View view){
  16. //StringRequest
  17. StringRequest request =newStringRequest(Request.Method.GET, REQUEST_URL,newResponse.Listener<String>(){
  18. @Override
  19. publicvoid onResponse(String s){//数据请求成功
  20. result.setText("请求成功:"+ s);
  21. }
  22. },newResponse.ErrorListener(){
  23. @Override
  24. publicvoid onErrorResponse(VolleyError volleyError){//数据请求失败
  25. result.setText("请求失败:"+ volleyError.getMessage());
  26. }
  27. });
  28. request.setTag("StringRequest_get");
  29. MyApplication.getQueues().add(request);
  30. }
  31. publicvoidStringRequestPost(View view){
  32. //StringRequest
  33. StringRequest request =newStringRequest(Request.Method.POST, BASE,newResponse.Listener<String>(){
  34. @Override
  35. publicvoid onResponse(String s){//数据请求成功
  36. result.setText("请求成功:"+ s);
  37. }
  38. },newResponse.ErrorListener(){
  39. @Override
  40. publicvoid onErrorResponse(VolleyError volleyError){//数据请求失败
  41. result.setText("请求失败:"+ volleyError.getMessage());
  42. }
  43. }){
  44. @Override//传递参数
  45. protectedMap<String,String> getParams()throwsAuthFailureError{
  46. Map<String,String> map =newHashMap<>();
  47. map.put("key","634f562a2b3900e051c6af6e2dc3017e");
  48. map.put("cityname","十堰");
  49. return map;
  50. }
  51. };
  52. request.setTag("StringRequestPost");
  53. MyApplication.getQueues().add(request);
  54. }
  55. publicvoidJsonObjectRequestGet(View view){
  56. //JsonObjectRequest
  57. JSONObject jsonRequest =newJSONObject();//Get请求传递参数jsonRequest可以为空null
  58. JsonObjectRequest request =newJsonObjectRequest(Request.Method.GET, REQUEST_URL,null,newResponse.Listener<JSONObject>(){
  59. @Override
  60. publicvoid onResponse(JSONObject jsonObject){
  61. result.setText("请求成功:"+ jsonObject);
  62. }
  63. },newResponse.ErrorListener(){
  64. @Override
  65. publicvoid onErrorResponse(VolleyError volleyError){
  66. result.setText("请求失败:"+ volleyError.getMessage());
  67. }
  68. });
  69. request.setTag("JsonObjectRequestGet");
  70. MyApplication.getQueues().add(request);
  71. }
  72. publicvoidJsonObjectRequestPost(View view){
  73. Map<String,String> map =newHashMap<>();
  74. map.put("key","634f562a2b3900e051c6af6e2dc3017e");
  75. map.put("cityname","十堰");
  76. JSONObject jsonRequest =newJSONObject(map);
  77. JsonObjectRequest request =newJsonObjectRequest(Request.Method.POST, BASE, jsonRequest,newResponse.Listener<JSONObject>(){
  78. @Override
  79. publicvoid onResponse(JSONObject jsonObject){
  80. result.setText("请求成功:"+ jsonObject.toString());
  81. }
  82. },newResponse.ErrorListener(){
  83. @Override
  84. publicvoid onErrorResponse(VolleyError volleyError){
  85. result.setText("请求失败:"+ volleyError.getMessage());
  86. }
  87. });
  88. request.setTag("JsonObjectRequestPost");
  89. MyApplication.getQueues().add(request);
  90. }
  91. publicvoidJsonArrayRequest(View view){
  92. JsonArrayRequest request =newJsonArrayRequest(REQUEST_URL,newResponse.Listener<JSONArray>(){
  93. @Override
  94. publicvoid onResponse(JSONArray jsonArray){
  95. result.setText("请求成功:"+ jsonArray);
  96. }
  97. },newResponse.ErrorListener(){
  98. @Override
  99. publicvoid onErrorResponse(VolleyError volleyError){
  100. result.setText("请求失败:"+ volleyError.getMessage());
  101. }
  102. });
  103. request.setTag("JsonArrayRequest");
  104. MyApplication.getQueues().add(request);
  105. }
  106. publicvoidMyRequestGet(View view){
  107. newVolleyRequest().RequestGet(this, REQUEST_URL,"MyRequestGet",newResultBack(this,ResultBack.listener,ResultBack.errorListener){
  108. @Override
  109. publicvoid onSuccess(String s){
  110. result.setText("请求成功:"+ s);
  111. }
  112. @Override
  113. publicvoid onFailure(VolleyError volleyError){
  114. result.setText("请求失败:"+ volleyError.getMessage());
  115. }
  116. });
  117. }
  118. publicvoidMyRequestPost(View view){
  119. Map<String,String> map =newHashMap<>();
  120. map.put("key","634f562a2b3900e051c6af6e2dc3017e");
  121. map.put("cityname","十堰");
  122. newVolleyRequest().RequestPost(this, REQUEST_URL,"MyRequestPost", map,newResultBack(this,ResultBack.listener,ResultBack.errorListener){
  123. @Override
  124. publicvoid onSuccess(String s){
  125. result.setText("请求成功:"+ s);
  126. }
  127. @Override
  128. publicvoid onFailure(VolleyError volleyError){
  129. result.setText("请求失败:"+ volleyError.getMessage());
  130. }
  131. });
  132. }
  133. //ImageRequest方式加载图片
  134. publicvoidImageRequest(View view){
  135. ImageRequest request =newImageRequest(IMAGE_URL,newResponse.Listener<Bitmap>(){
  136. @Override
  137. publicvoid onResponse(Bitmap bitmap){//加载成功
  138. image_imageRequest.setImageBitmap(bitmap);
  139. }
  140. },0,0,Bitmap.Config.RGB_565,newResponse.ErrorListener(){//加载失败
  141. @Override
  142. publicvoid onErrorResponse(VolleyError volleyError){
  143. image_imageRequest.setImageResource(R.mipmap.ic_launcher);
  144. }
  145. });
  146. request.setTag("ImageRequest");
  147. MyApplication.getQueues().add(request);
  148. }
  149. //ImageLoader加载图片
  150. publicvoidImageLoader(View view){
  151. ImageLoader imageLoader =newImageLoader(MyApplication.getQueues(),newBitmapCache());
  152. ImageLoader.ImageListener listener = imageLoader.getImageListener(image_iamgeLoader, R.mipmap.ic_launcher, R.mipmap.ic_launcher);
  153. imageLoader.get(IMAGE_URL, listener);
  154. }
  155. @Override
  156. protectedvoid onStop(){
  157. super.onStop();
  158. //结束请求
  159. MyApplication.getQueues().cancelAll("StringRequest_get");
  160. }
  161. }
  • Volley简单的二次回调封装
  1. publicclassVolleyRequest{
  2. publicstaticStringRequest stringRequest;
  3. publicstaticvoidRequestGet(Context context,String url,String tag,ResultBack reback){
  4. MyApplication.getQueues().cancelAll(tag);
  5. stringRequest=newStringRequest(Request.Method.GET, url,reback.loadingListener(),reback.errorListener());
  6. stringRequest.setTag(tag);
  7. MyApplication.getQueues().add(stringRequest);
  8. MyApplication.getQueues().start();
  9. }
  10. publicstaticvoidRequestPost(Context context,String url,String tag,finalMap<String,String> map,ResultBack reback){
  11. MyApplication.getQueues().cancelAll(tag);
  12. stringRequest=newStringRequest(Request.Method.GET, url, reback.loadingListener(),reback.errorListener()){
  13. @Override
  14. protectedMap<String,String> getParams()throwsAuthFailureError{
  15. return map;
  16. }
  17. };
  18. stringRequest.setTag(tag);
  19. MyApplication.getQueues().add(stringRequest);
  20. MyApplication.getQueues().start();
  21. }
  22. }

自定义的回调接口

  1. publicabstractclassResultBack{
  2. publicContext context;
  3. publicstaticResponse.Listener<String> listener;
  4. publicstaticResponse.ErrorListener errorListener;
  5. publicResultBack(Context context,Response.Listener<String> listener,Response.ErrorListener errorListener){
  6. this.context = context;
  7. this.listener = listener;
  8. this.errorListener = errorListener;
  9. }
  10. publicResponse.Listener<String> loadingListener(){
  11. listener =newResponse.Listener<String>(){
  12. @Override
  13. publicvoid onResponse(String s){
  14. onSuccess(s);
  15. }
  16. };
  17. return listener;
  18. }
  19. publicResponse.ErrorListener errorListener(){
  20. errorListener =newResponse.ErrorListener(){
  21. @Override
  22. publicvoid onErrorResponse(VolleyError volleyError){
  23. onFailure(volleyError);
  24. }
  25. };
  26. return errorListener;
  27. }
  28. publicabstractvoid onSuccess(String s);
  29. publicabstractvoid onFailure(VolleyError volleyError);
  30. }
  • 图像缓存类
  1. publicclassBitmapCacheimplementsImageLoader.ImageCache{
  2. publicLruCache<String,Bitmap> mBitmapLruCache;
  3. publicint max=1024*1024*10;// 最大缓存10M,超过就会回收
  4. publicBitmapCache(){
  5. mBitmapLruCache=newLruCache<String,Bitmap>(max){
  6. @Override
  7. protectedint sizeOf(String key,Bitmap value){
  8. return value.getRowBytes()*value.getHeight();
  9. }
  10. };
  11. }
  12. @Override
  13. publicBitmap getBitmap(String s){
  14. return mBitmapLruCache.get(s);
  15. }
  16. @Override
  17. publicvoid putBitmap(String s,Bitmap bitmap){
  18. mBitmapLruCache.put(s,bitmap);
  19. }
  20. }





posted @ 2015-08-19 23:00  星空守候  阅读(231)  评论(0编辑  收藏  举报