WebView downloads a website on the Internet, downloads a local file offline

I'm actually new to Java programming, but I have been following a few solutions to my problem, but have not found one that suits my case, and I cannot correctly understand the code.

I would like to have a WebView that opens an online page (like Google) when the phone is connected to the network, and open the local HTML page when the phone is offline.

At the same time, although I want the phone to overwrite the local page when it is online, so the local offline page is always updated to the last time the phone is connected to the Internet.

Any ideas on how to do this? Some simple directions to the right direction may help.

Thank you very much.

+55
android webview local offline auto-update
03 Feb '13 at 8:17
source share
2 answers

It looks like a simple web caching mechanism.

The following should do what you are looking for:

 WebView webView = new WebView( context ); webView.getSettings().setAppCacheMaxSize( 5 * 1024 * 1024 ); // 5MB 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.google.com" ); 

The isNetworkAvailable() method checks the active network connection:

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

Finally, be sure to add the following three permissions to your AndroidManifest.xml :

 <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"/> 
+95
03 Feb '13 at 9:53 on
source share
โ€” -

Here are examples of how WebView cannot be cached natively. If the page title contains the following fields, WebView will not be able to cache content from this page. Cache-Control: no-store, no-cache Pragma: no-cache

In this case, you will have to change the page property on the server to solve the caching problem.

+15
May 23 '13 at 18:53
source share



All Articles