android - how to prevent webview to load when no internet connection

前端 未结 5 2089
猫巷女王i
猫巷女王i 2020-12-02 18:45

I have an Android app which has a webview. When there\'s no internet connection, webview will display page not available. I want to make this look like an app as much as pos

5条回答
  •  悲&欢浪女
    2020-12-02 19:31

    You'll want to override the shouldOverrideUrlLoading method of a WebViewClient to catch URL clicks.

    To check the Wifi status, you'll want to use the ConnectivityManager

    Try this:

    WebView mWebView;
    NetworkInfo networkInfoWifi = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE).getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    
    mWebView.setWebViewClient(mWebClient);
    
    WebViewClient mWebClient = new WebViewClient(){
    
        @Override
        public boolean shouldOverrideUrlLoading(WebView  view, String  url){
            return true;
        }
    
        @Override
        public void onLoadResource(WebView  view, String  url){
            if (networkInfoWifi.isConnected()) {
                //Take action
            }
        }
    
    }
    

    I'd recommend breaking your problem into two smaller steps - Click Interception and Connection Status Checking, and searching for them. This yields plenty of results, and I was able to use these two existing answers to put together the code:

    Intercept Webview Click

    Check Wifi Connection

提交回复
热议问题