标签:request fit cal ora add div private public ast
Volley是常用的网络请求框架,主要的用法如下:
获取字符串:
public static void volleyTest1(final Context context){ RequestQueue queue = Volley.newRequestQueue(context); final String url = "http://www.baidu.com"; StringRequest request = new StringRequest(url, new Response.Listener<String>() { @Override public void onResponse(String s) { Toast.makeText(context, s, Toast.LENGTH_SHORT).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { Toast.makeText(context, volleyError.getMessage(), Toast.LENGTH_SHORT).show(); } } ); queue.add(request); }
获取图片:
public static void volleyImageTest1(final Context context, final ImageView imgView){ final String url = "http://img.my.csdn.net/uploads/201404/13/1397393290_5765.jpeg"; ImageRequest request = new ImageRequest(url, new Response.Listener<Bitmap>() { @Override public void onResponse(Bitmap bitmap) { Toast.makeText(context, "get image success!", Toast.LENGTH_SHORT).show(); imgView.setImageBitmap(bitmap); } }, 0, 0, ScaleType.FIT_XY, Config.RGB_565, new Response.ErrorListener(){ @Override public void onErrorResponse(VolleyError volleyError) { Toast.makeText(context, "get image failed!", Toast.LENGTH_SHORT).show(); } } ); RequestQueue queue = Volley.newRequestQueue(context); queue.add(request); }
异步加载图片:
public static void volleyImageTest2(final Context context, final ImageView imgView){ final BitmapCache bitmapCache = new BitmapCache(); RequestQueue queue = Volley.newRequestQueue(context); ImageLoader imgLoader = new ImageLoader(queue, bitmapCache); ImageLoader.ImageListener listener = imgLoader.getImageListener(imgView, R.mipmap.ic_launcher, R.mipmap.ic_launcher); // final String url = "http://img.my.csdn.net/uploads/201404/13/1397393290_5765.jpeg"; final String url = "http://img1.skqkw.cn:888/2014/12/06/08/21ofdtyslqn-62877.jpg"; imgLoader.get(url, listener); }
BitmapCache类:
private static class BitmapCache implements ImageCache{ private LruCache<String, Bitmap> lruCache; public BitmapCache(){ int maxSize = 8*1024*1024; lruCache = new LruCache<String, Bitmap>(maxSize){ @Override protected int sizeOf(String key, Bitmap bitmap) { return bitmap.getRowBytes()*bitmap.getHeight(); } }; } @Override public Bitmap getBitmap(String s) { return lruCache.get(s); } @Override public void putBitmap(String s, Bitmap bitmap) { lruCache.put(s, bitmap); }
Volley功能强大,能够对网络请求进行缓存,能够有效减少CPU消耗和减少网络请求。
标签:request fit cal ora add div private public ast
原文地址:http://www.cnblogs.com/MiniHouse/p/7100413.html