码迷,mamicode.com
首页 > 其他好文 > 详细

Volley框架

时间:2016-09-02 23:21:30      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:

Volley框架

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

特点

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

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


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

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

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

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

与Activity生命周期的联动

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

Volley调用实例源码展示

demo效果如下
技术分享

  • 布局文件
  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. public class MyApplication extends Application {
  2. //创建请求队列
  3. private static RequestQueue queues;
  4. @Override
  5. public void onCreate() {
  6. super.onCreate();
  7. //初始书请求队列
  8. queues = Volley.newRequestQueue(getApplicationContext());
  9. }
  10. public static RequestQueue getQueues() {
  11. return queues;
  12. }
  13. }
  • 主要实现文件
  1. public class MainActivity extends AppCompatActivity {
  2. public static final String BASE = "http://op.juhe.cn/onebox/weather/query";
  3. public static final String REQUEST_URL = BASE + "?cityname=%E5%8D%81%E5%A0%B0&key=634f562a2b3900e051c6af6e2dc3017e";
  4. public static final String IMAGE_URL = "https://pic.cnblogs.com/avatar/789527/20160825180355.png";
  5. private TextView result;
  6. private ImageView image_imageRequest, image_iamgeLoader;
  7. @Override
  8. protected void 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. public void StringRequestGet(View view) {
  16. //StringRequest
  17. StringRequest request = new StringRequest(Request.Method.GET, REQUEST_URL, new Response.Listener<String>() {
  18. @Override
  19. public void onResponse(String s) {//数据请求成功
  20. result.setText("请求成功:" + s);
  21. }
  22. }, new Response.ErrorListener() {
  23. @Override
  24. public void onErrorResponse(VolleyError volleyError) {//数据请求失败
  25. result.setText("请求失败:" + volleyError.getMessage());
  26. }
  27. });
  28. request.setTag("StringRequest_get");
  29. MyApplication.getQueues().add(request);
  30. }
  31. public void StringRequestPost(View view) {
  32. //StringRequest
  33. StringRequest request = new StringRequest(Request.Method.POST, BASE, new Response.Listener<String>() {
  34. @Override
  35. public void onResponse(String s) {//数据请求成功
  36. result.setText("请求成功:" + s);
  37. }
  38. }, new Response.ErrorListener() {
  39. @Override
  40. public void onErrorResponse(VolleyError volleyError) {//数据请求失败
  41. result.setText("请求失败:" + volleyError.getMessage());
  42. }
  43. }) {
  44. @Override//传递参数
  45. protected Map<String, String> getParams() throws AuthFailureError {
  46. Map<String, String> map = new HashMap<>();
  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. public void JsonObjectRequestGet(View view) {
  56. //JsonObjectRequest
  57. JSONObject jsonRequest = new JSONObject();//Get请求传递参数jsonRequest可以为空null
  58. JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, REQUEST_URL, null, new Response.Listener<JSONObject>() {
  59. @Override
  60. public void onResponse(JSONObject jsonObject) {
  61. result.setText("请求成功:" + jsonObject);
  62. }
  63. }, new Response.ErrorListener() {
  64. @Override
  65. public void onErrorResponse(VolleyError volleyError) {
  66. result.setText("请求失败:" + volleyError.getMessage());
  67. }
  68. });
  69. request.setTag("JsonObjectRequestGet");
  70. MyApplication.getQueues().add(request);
  71. }
  72. public void JsonObjectRequestPost(View view) {
  73. Map<String, String> map = new HashMap<>();
  74. map.put("key", "634f562a2b3900e051c6af6e2dc3017e");
  75. map.put("cityname", "十堰");
  76. JSONObject jsonRequest = new JSONObject(map);
  77. JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, BASE, jsonRequest, new Response.Listener<JSONObject>() {
  78. @Override
  79. public void onResponse(JSONObject jsonObject) {
  80. result.setText("请求成功:" + jsonObject.toString());
  81. }
  82. }, new Response.ErrorListener() {
  83. @Override
  84. public void onErrorResponse(VolleyError volleyError) {
  85. result.setText("请求失败:" + volleyError.getMessage());
  86. }
  87. });
  88. request.setTag("JsonObjectRequestPost");
  89. MyApplication.getQueues().add(request);
  90. }
  91. public void JsonArrayRequest(View view) {
  92. JsonArrayRequest request = new JsonArrayRequest(REQUEST_URL, new Response.Listener<JSONArray>() {
  93. @Override
  94. public void onResponse(JSONArray jsonArray) {
  95. result.setText("请求成功:" + jsonArray);
  96. }
  97. }, new Response.ErrorListener() {
  98. @Override
  99. public void onErrorResponse(VolleyError volleyError) {
  100. result.setText("请求失败:" + volleyError.getMessage());
  101. }
  102. });
  103. request.setTag("JsonArrayRequest");
  104. MyApplication.getQueues().add(request);
  105. }
  106. public void MyRequestGet(View view) {
  107. new VolleyRequest().RequestGet(this, REQUEST_URL, "MyRequestGet", new ResultBack(this, ResultBack.listener, ResultBack.errorListener) {
  108. @Override
  109. public void onSuccess(String s) {
  110. result.setText("请求成功:" + s);
  111. }
  112. @Override
  113. public void onFailure(VolleyError volleyError) {
  114. result.setText("请求失败:" + volleyError.getMessage());
  115. }
  116. });
  117. }
  118. public void MyRequestPost(View view) {
  119. Map<String, String> map = new HashMap<>();
  120. map.put("key", "634f562a2b3900e051c6af6e2dc3017e");
  121. map.put("cityname", "十堰");
  122. new VolleyRequest().RequestPost(this, REQUEST_URL, "MyRequestPost", map, new ResultBack(this, ResultBack.listener, ResultBack.errorListener) {
  123. @Override
  124. public void onSuccess(String s) {
  125. result.setText("请求成功:" + s);
  126. }
  127. @Override
  128. public void onFailure(VolleyError volleyError) {
  129. result.setText("请求失败:" + volleyError.getMessage());
  130. }
  131. });
  132. }
  133. //ImageRequest方式加载图片
  134. public void ImageRequest(View view) {
  135. ImageRequest request = new ImageRequest(IMAGE_URL, new Response.Listener<Bitmap>() {
  136. @Override
  137. public void onResponse(Bitmap bitmap) {//加载成功
  138. image_imageRequest.setImageBitmap(bitmap);
  139. }
  140. }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {//加载失败
  141. @Override
  142. public void 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. public void ImageLoader(View view) {
  151. ImageLoader imageLoader = new ImageLoader(MyApplication.getQueues(), new BitmapCache());
  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. protected void onStop() {
  157. super.onStop();
  158. //结束请求
  159. MyApplication.getQueues().cancelAll("StringRequest_get");
  160. }
  161. }
  • Volley简单的二次回调封装
  1. public class VolleyRequest {
  2. public static StringRequest stringRequest;
  3. public static void RequestGet(Context context,String url,String tag,ResultBack reback){
  4. MyApplication.getQueues().cancelAll(tag);
  5. stringRequest=new StringRequest(Request.Method.GET, url,reback.loadingListener(),reback.errorListener());
  6. stringRequest.setTag(tag);
  7. MyApplication.getQueues().add(stringRequest);
  8. MyApplication.getQueues().start();
  9. }
  10. public static void RequestPost(Context context, String url,String tag,final Map<String,String> map,ResultBack reback){
  11. MyApplication.getQueues().cancelAll(tag);
  12. stringRequest=new StringRequest(Request.Method.GET, url, reback.loadingListener(),reback.errorListener()){
  13. @Override
  14. protected Map<String, String> getParams() throws AuthFailureError {
  15. return map;
  16. }
  17. };
  18. stringRequest.setTag(tag);
  19. MyApplication.getQueues().add(stringRequest);
  20. MyApplication.getQueues().start();
  21. }
  22. }

自定义的回调接口

  1. public abstract class ResultBack {
  2. public Context context;
  3. public static Response.Listener<String> listener;
  4. public static Response.ErrorListener errorListener;
  5. public ResultBack(Context context, Response.Listener<String> listener, Response.ErrorListener errorListener) {
  6. this.context = context;
  7. this.listener = listener;
  8. this.errorListener = errorListener;
  9. }
  10. public Response.Listener<String> loadingListener() {
  11. listener = new Response.Listener<String>() {
  12. @Override
  13. public void onResponse(String s) {
  14. onSuccess(s);
  15. }
  16. };
  17. return listener;
  18. }
  19. public Response.ErrorListener errorListener() {
  20. errorListener = new Response.ErrorListener() {
  21. @Override
  22. public void onErrorResponse(VolleyError volleyError) {
  23. onFailure(volleyError);
  24. }
  25. };
  26. return errorListener;
  27. }
  28. public abstract void onSuccess(String s);
  29. public abstract void onFailure(VolleyError volleyError);
  30. }
  • 图像缓存类
  1. public class BitmapCache implements ImageLoader.ImageCache {
  2. public LruCache<String,Bitmap> mBitmapLruCache;
  3. public int max=1024*1024*10;// 最大缓存10M,超过就会回收
  4. public BitmapCache(){
  5. mBitmapLruCache=new LruCache<String,Bitmap>(max){
  6. @Override
  7. protected int sizeOf(String key, Bitmap value) {
  8. return value.getRowBytes()*value.getHeight();
  9. }
  10. };
  11. }
  12. @Override
  13. public Bitmap getBitmap(String s) {
  14. return mBitmapLruCache.get(s);
  15. }
  16. @Override
  17. public void putBitmap(String s, Bitmap bitmap) {
  18. mBitmapLruCache.put(s,bitmap);
  19. }
  20. }




Volley框架

标签:

原文地址:http://www.cnblogs.com/wisemen/p/5835918.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!