Performance issue with Volley's DiskBasedCache

前端 未结 3 1084
耶瑟儿~
耶瑟儿~ 2020-12-23 16:55

In my Photo Collage app for Android I\'m using Volley for loading images. I\'m using the DiskBasedCache (included with volley) with 50 mb storage to prevent re-downloading

3条回答
  •  滥情空心
    2020-12-23 17:42

    My initial thought was to use the DiskLruCache written by Jake Wharton by writing a com.android.volley.Cache wrapper over it.

    But I finally implemented a singleton pattern for the Volley, combined with the cache creation in an AsyncTask called from the Application context

    public static synchronized VolleyClient getInstance(Context context)
    {
        if (mInstance == null)
        {
            mInstance = new VolleyClient(context);
        }
        return mInstance;
    }
    
    private VolleyClient(Context context)
    {
        this.context = context;
        VolleyCacheInitializer volleyCacheInitializer = new VolleyCacheInitializer();
        volleyCacheInitializer.execute();
    }
    
    private class VolleyCacheInitializer extends AsyncTask
    {
        @Override
        protected Boolean doInBackground(Void... params)
        {
            // Instantiate the cache with 50MB Cache Size
            Cache diskBasedCache = new DiskBasedCache(context.getCacheDir(), 50 * 1024 * 1024);
    
            // Instantiate the RequestQueue with the cache and network.
            mRequestQueue = new RequestQueue(diskBasedCache, network);
    
            // Start the queue which calls the DiskBasedCache.initialize()
            mRequestQueue.start();
    
            return true;
        }
    
        @Override
        protected void onPostExecute(Boolean aBoolean)
        {
            super.onPostExecute(aBoolean);
    
            if(aBoolean)
                Log.d(TAG, "Volley request queue initialized");
            else
                Log.d(TAG, "Volley request queue initialization failed");
        }
    }
    

    Inside MyApplication class

    @Override
    public void onCreate()
    {
        super.onCreate();
    
        // Initialize an application level volley request queue
        VolleyClient volleyHttpClient = VolleyClient.getInstance(this);
    }
    

提交回复
热议问题