【问题标题】:Load Cache in Android Webview when not connected to internet else show the content from the server when connected to internet未连接到 Internet 时在 Android Webview 中加载缓存,否则在连接到 Internet 时显示来自服务器的内容
【发布时间】:2011-08-22 11:45:47
【问题描述】:

我有这个应用程序,它在离线模式下使用 webview 呈现缓存的内容,并在连接到互联网时显示来自服务器的网页...

代码 sn-ps 如下所示。当我运行应用程序时它崩溃了。

我无法弄清楚出了什么问题。我还在清单文件中设置了使用权限 android:name="android.permission.INTERNET"。

package com.html5webappcache.android;

import android.app.Activity;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebStorage.QuotaUpdater;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

public class HTML5WebAppCacheTestActivity extends Activity {
    final Activity activity = this;
    private ConnectivityManager cm;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Adds Progrss bar Support
        this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
        setContentView(R.layout.main );

        getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON); 

        WebView engine=(WebView)findViewById(R.id.web_engine);
        engine.getSettings().setJavaScriptEnabled(true);
        engine.getSettings().setBuiltInZoomControls(true);
        engine.getSettings().setLoadsImagesAutomatically(true);
        engine.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        engine.setInitialScale(1);

        engine.setWebChromeClient(new WebChromeClient() {
              @Override
                 public void onReachedMaxAppCacheSize(long spaceNeeded, long totalUsedQuota,QuotaUpdater quotaUpdater)
                 {
                       quotaUpdater.updateQuota(spaceNeeded * 2);
                 }
              public void onProgressChanged(WebView view, int progress)
              {
                  activity.setTitle("Loading...");
                  activity.setProgress(progress * 100);



                  if(progress == 100)
                  { activity.setTitle(R.string.app_name);

                  }
              }
           });
        engine.getSettings().setDomStorageEnabled(true);
       // Set cache size to 8 mb by default. should be more than enough
        engine.getSettings().setAppCacheMaxSize(1024*1024*8);
        engine.getSettings().setAppCachePath("/data/data/com.html5webappcache.android/cache");
        engine.getSettings().setAllowFileAccess(true);
        engine.getSettings().setAppCacheEnabled(true);
        engine.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

         cm = (ConnectivityManager) this.getSystemService(Activity.CONNECTIVITY_SERVICE);
         if(cm.getActiveNetworkInfo().isConnected())
         {
         engine.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
         engine.loadUrl("http://www.bifter.co.uk/");
         }
             else{
                engine.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                 engine.loadUrl("http://www.bifter.co.uk/");
             }











    }
}

【问题讨论】:

    标签: android caching android-webview


    【解决方案1】:

    也许 NetworkInfo 对象为 null,而您得到 NullPointerException。找出代码行的最佳方法是使用 logcat 并查看堆栈跟踪。

    顺便说一句,我使用类似的方式在 WebViews 中使用缓存,但在我的设备 (Desire + CM7) 上它不起作用,因为缓存从未使用过..

    致以诚挚的问候, 杰恩

    【讨论】:

      【解决方案2】:
      webview1 = (WebView) findViewById(R.id.webView1);
      
          WebSettings webSettings = webview1.getSettings();
          webSettings.setJavaScriptEnabled(true);
          webSettings.setCacheMode(WebSettings.LOAD_NORMAL); <--- CHANGE THIS
          webSettings.setAppCacheMaxSize(1024*1024*8);
          webview1.addJavascriptInterface(new JavaScriptInterface(this),
                  "Android");
          webview1.setWebViewClient(new MyWebViewClient());
          webview1.setBackgroundColor(Color.BLACK);
      
      
          try {
              current_url = "http://........link";
              webview1.loadUrl(current_url);
          } catch (Exception e) {
              Log.v("Loading Webview Failed", "Loading the webview Failed");
          }
      
          current_fact = 0;
      

      【讨论】:

        【解决方案3】:

        只需添加 &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt; 在 AndroidManifest.xml 中。它会像魔术一样工作。 LogCat 提供了帮助。

        【讨论】:

          【解决方案4】:

          您还需要检查 networkInfo 是否为空 所以基本上你的 if 语句应该是

          if(cm.getActiveNetworkInfo() == null || !cm.getActiveNetworkInfo().isConnected()){
          //load cache
          }else{
          //load default
          }
          

          别忘了添加这些权限

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

          至于 AppCachePath,如果您正在为 android 2.2+ 构建,那么请改用它

          engine.getSettings().setAppCachePath(getApplication().getCacheDir().toString());
          

          这将保证缓存将在应用卸载时被删除

          【讨论】:

            猜你喜欢
            • 2017-03-31
            • 1970-01-01
            • 2022-01-11
            • 2015-03-06
            • 1970-01-01
            • 2019-09-03
            • 2011-11-05
            • 2017-09-05
            • 1970-01-01
            相关资源
            最近更新 更多