Tuesday, August 5, 2014

Android web view

http://pavantilak.blogspot.com/2012/02/code-to-display-pdftextdocdocxdoc.html

http://stackoverflow.com/questions/14670638/webview-load-website-when-online-load-local-file-when-offline

http://stackoverflow.com/questions/8911666/storing-a-webview-for-offline-browsing-android

http://alex.tapmania.org/2010/11/html5-cache-android-webview.html

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 method isNetworkAvailable() checks for an active network connection:
private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService( CONNECTIVITY_SERVICE );
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null;
}
Finally, don't forget 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"/>
Hello, First of all, thank you for the very useful answer. I am very grateful but I just give you a small piece of code that make my app work perfectly. Because the function isNetworkAvailable that you posted here seems to not work for me.
private boolean isNetworkAvailable() {
  boolean isConnected = false;
  ConnectivityManager check = (ConnectivityManager)        
  this.getSystemService(Context.CONNECTIVITY_SERVICE);
  if (check != null){ 
    NetworkInfo[] info = check.getAllNetworkInfo();
    if (info != null){
     for (int i = 0; i <info.length; i++){
       if (info[i].getState() == NetworkInfo.State.CONNECTED){
         isConnected = true;
       }
    }
    return isConnected;
  }

No comments:

Post a Comment