Android webview未显示服务工作者保存的脱机页面

问题描述 投票:0回答:1

我有一个服务工作者的网页,在离线模式下,移动Chrome仍然可以显示我的offline.html。

现在我有一个带有webview的Android APP来显示页面,但是当没有互联网时,有一个Android错误页面说"Webpage not available The webpage at xxxxxx could not be loaded because: net:ERR_FAILED"

我该如何解决?我可以阻止在Android APP中检查互联网连接吗?非常感谢你!

android webview android-webview service-worker offline
1个回答
1
投票

您需要覆盖自己的WebViewClient并检查shouldOverrideUrlLoading中的Internet连接

public boolean checkInternetConnection(Context context) {   

    ConnectivityManager con_manager = (ConnectivityManager) 
      context.getSystemService(Context.CONNECTIVITY_SERVICE);

    return (con_manager.getActiveNetworkInfo() != null
        && con_manager.getActiveNetworkInfo().isAvailable()
        && con_manager.getActiveNetworkInfo().isConnected());
}

class CustomWebViewClient extends WebViewClient {
  @Override
  public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (!checkInternetConnection(this)) {
      view.loadUrl("file:///android_asset/filename.html");
    } else {
      view.loadUrl(url);
    }     
    return true;
  }
}

当然,将你的自定义WebViewClient设置为你的WebView

webview.setWebViewClient(new CustomWebViewClient())

另外,将filename.html放入Android项目资产文件夹中

© www.soinside.com 2019 - 2024. All rights reserved.