[英]Android Volley Singleton Pattern how to add/cancel requests based on tag
根据https://developer.android.com/training/volley/requestqueue.html#singleton的建议,不鼓励通过在Application.onCreate()中设置RequestQueue使用实现单例类的旧方法。
如下所示,提供的“新的”模块化更多方式不包含将标签添加到请求并使用这些标签取消它们的方法。
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 LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(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() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
}
我该如何添加与旧方法(在Application.onCreate()中)类似的方法:
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
关于RequestQueue的任何方面都没有改变。 您只是从与Application类不同的单例访问它。 始终将标签添加到请求中:
ImageRequest request = new ImageRequest(...);
request.setTag(MY_TAG);
MySingleton.getInstance(this).addToRequestQueue(request);
-编辑-
进一步详细说明:这与从其他任何地方获取RequestQueue对象相同。 它仍然只是一个RequestQueue。
所以这:
mRequestQueue.cancelAll(tag);
成为:
MySingleton.getRequestQueue().cancelAll(tag);
对于您以前使用RequestQueue所做的任何其他操作,也是如此。 示例MySingleton类只是为您保留了请求队列。 它没有改变。
要取消所有内容,无论使用什么标签:
MySingleton.getRequestQueue().cancelAll(new RequestQueue.RequestFilter() {
@Override
public boolean apply(Request<?> request) {
return true;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.