【问题标题】:Cache set of web pages in a webview android在webview android中缓存一组网页
【发布时间】:2020-05-26 09:10:53
【问题描述】:

我正在开发一个 Web 应用程序,并且我还将在 Android 中使用 WebView 应用程序,我想缓存一些页面集以便为我的用户提供离线访问。目前只缓存那些我访问过的页面,但我想预先缓存一组页面,以便用户可以离线工作。

我现在使用的代码:

private WebView webView = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    this.webView = (WebView)
            findViewById(R.id.webview);

    webView.setWebViewClient(new WebViewClient());
    WebSettings webSettings = webView.getSettings();

    String appCachePath;
    appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
    // Enable responsive layout
    webSettings.setUseWideViewPort(true);
    // Zoom out if the content width is greater than the width of the viewport
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setAppCachePath(appCachePath);
    webSettings.setAppCacheEnabled(true);
    webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);

    ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Activity.CONNECTIVITY_SERVICE);
    if(cm.getActiveNetworkInfo() == null || !cm.getActiveNetworkInfo().isConnected())
    {
        Log.i("B","INSIDE NO NETWORK");
        appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        webSettings.setAppCachePath(appCachePath);

        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);
        webView.loadUrl("https://www.example.com");
    }
    else
    {
        Log.i("A","INSIDE YES NETWORK");
        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        webView.loadUrl("https://www.example.com");
    }
 }

【问题讨论】:

  • 嘿,你找到解决办法了吗?
  • 不,我现在不使用 webview,经过一点 RnD,我发现 pwa 对我的用例更有用,因此我将使用 serviceworkers @akki 进行缓存

标签: android caching webview


【解决方案1】:
public class XXXWebViewClient extends WebViewClient {
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        if ("https://www.example.com".equals(url)) {
            String mimeType;//the resource response's MIME type, for example text/html
            String encoding;//the resource response's encoding
            Inputstream is;//cache of pages
            ...
            return new WebResourceResponse(mimeType,codeing,is);
        }
        return null;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 2020-03-29
    • 2011-12-29
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 2013-02-01
    相关资源
    最近更新 更多