简体   繁体   中英

Cache to Local Storage in WebView android

I am showing a html page in to webview using URL and I want to store that html file from webview cache to local storage of device. Is it possible, Please help.

Webview caching

WebView webView = new WebView( context );
webView.getSettings().setAppCacheMaxSize( 6 * 1024 * 1024 ); // 6MB size
webView.getSettings().setAppCachePath( getApplicationContext().getCacheDir().getAbsolutePath() );
webView.getSettings().setAllowFileAccess( true );
webView.getSettings().setAppCacheEnabled( true );
webView.getSettings().setJavaScriptEnabled( true );
webView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT ); // load online by default

if ( !isNetworkAvailable() ) { // loading offline
    webView.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK );
}

webView.loadUrl( "http://www.stackoverflow.com" );

Check internet availability and add permission to your manifest file

private boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService( CONNECTIVITY_SERVICE );
    NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
} 

permission for internet read and write storage

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM