Instantiating core Volley objects

前端 未结 1 674
北恋
北恋 2021-01-02 13:12

What I\'m a bit unsure about with Volley is the RequestQueue, ImageLoader objects and ImageLoader.ImageCache implementations..

In the examples I have come across th

相关标签:
1条回答
  • 2021-01-02 13:46

    My experience with Volley is that I would initiate a RequestQueue inside of the Application class passing it a global context to the application. I can't see the downside to doing this just make a static reference to the RequestQueue as such:

    public class MyApplication extends Application
    {
        private static RequestQueue mRequestQueue;
    
        @Override
        public void onCreate() {
            super.onCreate();
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }
    
        // Getter for RequestQueue or just make it public
    }
    

    In the documentation as you can for the Application class it quotes:

    Called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created. Implementations should be as quick as possible (for example using lazy initialization of state) since the time spent in this function directly impacts the performance of starting the first activity, service, or receiver in a process. If you override this method, be sure to call super.onCreate().

    So it is safe to assume our RequestQueue will be available to dispatch Requests in a Service, Activity, Loader etc.

    Now as far as the ImageLoader is concerned I would make a singleton class wrapping some functionality so you only have one instance of ImageCache and one ImageLoader, Ex.

    public class ImageLoaderHelper
    {
        private static ImageLoaderHelper mInstance = null;
    
        private final ImageLoader mImageLoader;
        private final ImageCache mImageCache;
    
        public static ImageLoaderHelper getInstance() {
            if(mInstance == null)
                mInstance = new ImageLoaderHelper();
            return mInstance;
        }
    
        private ImageLoaderHelper() {
            mImageCache = new MyCustomImageCache();
            mImageLoader = new ImageLoader(MyApplication.getVolleyQueue(),mImageCache);
        }
    
        // Now you can do what ever you want with your ImageCache and ImageLoader
    }
    

    If you want a really good example of ImageLoading with volley check out this sample project it is really useful.

    Hope this helps.

    0 讨论(0)
提交回复
热议问题