Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move webView cache to SD?

I've seen some apps like dolphin browser (not the HD version, the normal one) utilizing a cache-to-sd for webview but i can't seem to figure out how to do this, does anyone know how to do this or point me in the right direction? Any help is greatly appreciated! Thanks :)

like image 447
Malcolm Lim Avatar asked Aug 02 '10 15:08

Malcolm Lim


People also ask

Can we cache WebView in android?

You can use the WebView cache to enable caching in WebView.

Does WebView have cache?

WebViews are android views, that when created, consume context . And if we cache activity context on the application level, we might end up leaking the activity that was used to create the web-view.

How do I enable cache in WebView?

This example demonstrate about How to enable app cache for webview in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How do I disable cache in WebView?

setAppCacheEnabled(false); webview. getSettings(). setCacheMode(WebSettings. LOAD_NO_CACHE);


2 Answers

Here is the article which describes exactly how to change webview cache storage to use sd card: http://www.devahead.com/blog/2012/01/saving-the-android-webview-cache-on-the-sd-card/

I've already tested it in my application and it has proven to work.

public class MainApplication extends Application {
    // ...

    @Override
    public File getCacheDir() {
        // NOTE: this method is used in Android 2.2 and higher
        File cachePath = this.getExternalCachePath();
        return cachePath != null ? cachePath : super.getCacheDir();
    }

    private File getExternalCachePath() {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            File externalStorageDir = Environment.getExternalStorageDirectory();
            // {SD_PATH}/Android/data/com.package.name/cache
            File extStorageAppCachePath = new File(externalStorageDir, "Android" + File.separator + "data" + File.separator + this.getPackageName() + File.separator + "cache");

            return extStorageAppCachePath;
        }

        return null;
    }
}

public class SomeWebViewActivity extends Activity {
    // ...

    @Override
    public File getCacheDir() {
        // Android 2.1 and lower
        return this.getApplicationContext().getCacheDir();
    }
}
like image 135
vortexwolf Avatar answered Oct 03 '22 05:10

vortexwolf


Well, the WebSettings object has a number of set...Path() methods. It is unclear if any of them are for the actual cache. There is also the CacheManager object, which has a bunch of static methods related to the cache, but no obvious way to change the cache location.

like image 41
CommonsWare Avatar answered Oct 03 '22 04:10

CommonsWare