标签:
官方文档地址:https://developer.android.com/training/volley/requestqueue.html
之前一直没看到这个,原来官方已经正式有关于Volley的文档了,而且这是被建议使用的Network库。
因为之前有写过简单的Volley请求怎么写,下面介绍的都是我之前不知道的用法:
1.先上代码:
1 Cache cache = new DiskBasedCache(getCacheDir(),1024*1024); 2 Network network = new BasicNetwork(new HurlStack()); 3 RequestQueue requestQueue = new RequestQueue(cache,network); 4 requestQueue.start(); 5 StringRequest stringRequest = new StringRequest(Request.Method.GET,"http://www.baidu.com",new Response.Listener<String>() { 6 @Override 7 public void onResponse(String s) { 8 Log.i("TAG",s); 9 } 10 },new Response.ErrorListener() { 11 @Override 12 public void onErrorResponse(VolleyError volleyError) { 13 Log.e("TAG",""+volleyError); 14 } 15 }); 16 17 requestQueue.add(stringRequest);
这时,我们看到,建立了一个缓存区,同时使用了封装好的网络请求,注意,此时跟原来不同的问题来了,这里自定义的请求队列需要自己启动(start),其他操作相同。
2.使用一个单例来包装上述过程
public class MySingleton { private RequestQueue mRequestQueue; private static MySingleton mInstance; private ImageLoader mImageLoader; private Context mContext; private MySingleton(Context context){ mContext = context; mRequestQueue = getRequestQueue(); mImageLoader = new ImageLoader(mRequestQueue,new ImageLoader.ImageCache() { private final LruCache<String,Bitmap> cache = new LruCache<>(20); @Override public Bitmap getBitmap(String s) { return cache.get(s); } @Override public void putBitmap(String s, Bitmap bitmap) { cache.put(s,bitmap); } }); } public RequestQueue getRequestQueue() { if(mRequestQueue == null){ mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext()); } return mRequestQueue; } public static synchronized MySingleton getInstance(Context context) { if (mInstance == null){ mInstance = new MySingleton(context); } return mInstance; } public <T> void addToRequestQueue(Request<T> req){ getRequestQueue().add(req); } public ImageLoader getImageLoader() { return mImageLoader; } }
这样,就可以使用这个来请求很多不同的请求了,虽然在某些时候缓存不大有用。
3.如何加载图片请求
1 public class MainActivity extends AppCompatActivity { 2 3 @Override 4 protected void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 setContentView(R.layout.activity_main); 7 8 final ImageView imageView = (ImageView)findViewById(R.id.image); 9 String url = "http://p2.zhimg.com/10/7b/107bb4894b46d75a892da6fa80ef504a.jpg"; 10 11 ImageRequest request = new ImageRequest(url,new Response.Listener<Bitmap>() { 12 @Override 13 public void onResponse(Bitmap bitmap) { 14 imageView.setImageBitmap(bitmap); 15 } 16 },0,0,null,new Response.ErrorListener() { 17 @Override 18 public void onErrorResponse(VolleyError volleyError) { 19 Log.i("TAG","Error"); 20 } 21 }); 22 23 MySingleton.getInstance(this).addToRequestQueue(request); 24 } 25 }
但是注意此时ImageRequest已经过期。
4.使用ImageLoader和ImageView
1 ImageLoader imageLoader = MySingleton.getInstance(this).getImageLoader(); 2 imageLoader.get(url,ImageLoader.getImageListener(imageView,R.drawable.zhanwei,android.R.drawable.stat_notify_error));
5.使用ImageLoader和NetworkImageView(都由Volley提供)
1 2 String IMAGE_URL = "https://avatars0.githubusercontent.com/u/9381246?v=3&s=460"; 3 NetworkImageView imageView = (NetworkImageView)findViewById(R.id.image); 4 ImageLoader imageLoader = MySingleton.getInstance(this).getImageLoader(); 5 6 imageView.setImageUrl(IMAGE_URL,imageLoader);
6.自定义一些LruCache,并结合ImageCache
1 public class LruBitmapCache extends LruCache<String,Bitmap> implements ImageLoader.ImageCache { 2 3 public LruBitmapCache(int maxSize) { 4 super(maxSize); 5 } 6 7 public LruBitmapCache(Context context){ 8 this(getCacheSize(context)); 9 } 10 11 public static int getCacheSize(Context context) { 12 final DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); 13 final int screenWidth = displayMetrics.widthPixels; 14 final int screenHeight = displayMetrics.heightPixels; 15 final int screenBytes = screenHeight * screenWidth * 4; 16 return screenBytes*3; 17 } 18 19 @Override 20 protected int sizeOf(String key, Bitmap value) { 21 return value.getRowBytes() * value.getHeight(); 22 } 23 24 @Override 25 public Bitmap getBitmap(String s) { 26 return get(s); 27 } 28 29 30 @Override 31 public void putBitmap(String s, Bitmap bitmap) { 32 put(s,bitmap); 33 } 34 35 36 }
1 ImageView imageView = (ImageView)findViewById(R.id.image); 2 String IMAGE_URL = "https://avatars0.githubusercontent.com/u/9381246?v=3&s=460"; 3 4 RequestQueue requestQueue = MySingleton.getInstance(this).getRequestQueue(); 5 ImageLoader imageLoader = new ImageLoader(requestQueue,new LruBitmapCache(this)); 6 imageLoader.get(IMAGE_URL,ImageLoader.getImageListener(imageView,R.drawable.zhanwei,R.drawable.zhanwei));
还有Json的Request,以前介绍过了,就不再叙述了。
7.自定义Request
由于volley中实现了三种基本请求 : string / image / json的请求,所以除了这三种基本请求之外,你如果还想要请求其他数据,可以自定义Request。
下面是文档中的Gson请求的写法:
1 public class GsonRequest<T> extends Request<T> { 2 3 private final Gson gson = new Gson(); 4 private final Class<T> clazz; 5 private final Map<String,String> headers; 6 private final Response.Listener<T> listener; 7 8 public GsonRequest(String url,Class<T>clazz,Map<String,String> headers,Response.Listener<T> listener, Response.ErrorListener errorListener) { 9 super(Method.GET, url, errorListener); 10 this.clazz = clazz; 11 this.headers = headers; 12 this.listener = listener; 13 } 14 15 @Override 16 public Map<String, String> getHeaders() throws AuthFailureError{ 17 return headers != null ? headers : super.getHeaders(); 18 } 19 20 @Override 21 protected Response<T> parseNetworkResponse(NetworkResponse networkResponse) { 22 try{ 23 String json = new String(networkResponse.data, 24 HttpHeaderParser.parseCharset(networkResponse.headers)); 25 return Response.success(gson.fromJson(json,clazz), 26 HttpHeaderParser.parseCacheHeaders(networkResponse)); 27 }catch (UnsupportedEncodingException|JsonSyntaxException e){ 28 return Response.error(new ParseError()); 29 } 30 } 31 32 @Override 33 protected void deliverResponse(T t) { 34 listener.onResponse(t); 35 } 36 }
Gson是google开发的一种(Gson is a Java library that can be used to convert Java Objects into their JSON representation.)用于Java类和Json格式相互转化的工具,项目地址https://code.google.com/p/google-gson/
标签:
原文地址:http://www.cnblogs.com/lhyz/p/4496968.html