本文共 2331 字,大约阅读时间需要 7 分钟。
原文地址:http://www.jianshu.com/p/40d27cbceb98
如果你只是产生一次性的request而不想留下线程池,你可以使用中描述的Volley.newRequestQueue()
在任何你需要的地方创建RequestQueue
,然后一旦响应或错误返回了,在RequestQueue
调用stop()
。但是更普遍的用法是使用单例创建RequestQueue
,让RequestQueue
伴随着app的生命周期一直运行,这个在下一个部分讨论。
使用单例模式
如果你的应用需要经常使用网络,那么创建单例的RequestQueue
会更高效。你可以通过多种方式实现。推荐的方式是实现一个单例类来封装RequestQueue
和其它的Volley有的功能。另一种方式是继承Application
并在Application.onCreate()
方法中构建RequestQueue
。但是我们不鼓励这样做。一个静态的单例能够更加模块化地提供相同的功能。
关键的是RequestQueue
必须用Application
的context来初始化,而不是Activity
的context。这样才能保证RequestQueue
能够伴随着应用的生命周期存在,而不是随着activity的每次重建而重建(比如,当用户旋转设备)。
下面是一个单例类的例子,提供了RequestQueue
和ImageLoader
的功能:
public class MySingleton { private static MySingleton mInstance; private RequestQueue mRequestQueue; private ImageLoader mImageLoader; private static Context mCtx; private MySingleton(Context context) { mCtx = context; mRequestQueue = getRequestQueue(); mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() { private final LruCachecache = new LruCache (20); @Override public Bitmap getBitmap(String url) { return cache.get(url); } @Override public void putBitmap(String url, Bitmap bitmap) { cache.put(url, bitmap); } }); } public static synchronized MySingleton getInstance(Context context) { if (mInstance == null) { mInstance = new MySingleton(context); } return mInstance; } public RequestQueue getRequestQueue() { if (mRequestQueue == null) { // getApplicationContext() 是关键, 它避免了你 //传递进Activity或BroadcastReceiver导致的内存泄漏 mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext()); } return mRequestQueue; } public void addToRequestQueue(Request req) { getRequestQueue().add(req); } public ImageLoader getImageLoader() { return mImageLoader; }}
下面是使用单例类来执行RequestQueue
操作的例子:
// 获取一个RequestQueueRequestQueue queue = MySingleton.getInstance(this.getApplicationContext()). getRequestQueue();// ...// 添加一个request (示例中为 stringRequest) 到RequestQueue中MySingleton.getInstance(this).addToRequestQueue(stringRequest);
项目源码下载 :
转载地址:https://blog.csdn.net/happy_love1990/article/details/70218092 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!