最近自己在写一个框架,写完后找了一个项目试用了下,主要目的是发现现有框架存在的问题。同时看到有不少人使用Volley的方式不正确,其实在官网上明确说明了使用方法。下面应用Google官网上原话。
f your application makes constant use of the network, it's probably most efficient to set up a single instance ofRequestQueue that will last the lifetime of your app. You can achieve this in various ways. The recommended approach is to implement a singleton class that encapsulates RequestQueue and other Volley functionality. Another approach is to subclass Application and set up the RequestQueue in Application.onCreate(). But this approach is discouraged; a static singleton can provide the same functionality in a more modular way.
A key concept is that the RequestQueue must be instantiated with the Application context, not an Activitycontext. This ensures that the RequestQueue will last for the lifetime of your app, instead of being recreated every time the activity is recreated (for example, when the user rotates the device).
大致意思就是,在你的App运行过程中只用创建一次RequestQueue(之前我看到有人写的框架中,将Activtiy抽取成BaseActivity了,在每个BaseActivity中都创建了一个RequestQueue),Google推荐你用单例模式来创建这个RequestQueue,而且创建RequestQueue的时候传入的Context用 Application context,不要用Activitycontext,虽然在你的项目中,可以继承Application类,然后在onCreate()方法里来创建RequestQueue也可以达到在App运行过程中只创建了一次RequestQueue(我当时就是这样做的),但是Google同样不推荐。这里Google也给出了创建RequestQueue 和ImageLoader的源码,ImageLoader帮助获取网络图片时进行缓存
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;
}
}
最后,下面是使用RequestQueue的的代码
// Get a RequestQueue
RequestQueue queue = MySingleton.getInstance(this.getApplicationContext()).
getRequestQueue();
...
// Add a request (in this example, called stringRequest) to your RequestQueue.
MySingleton.getInstance(this).addToRequestQueue(stringRequest);