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

前端 未结 5 2080
猫巷女王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:41

    I have used the following in my projects:

    DetectConnection.Java

    import android.content.Context;
    import android.net.ConnectivityManager;
    
    
    public class DetectConnection {             
      public static 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());
      }
    }
    

    Main code:

    if (!DetectConnection.checkInternetConnection(this)) {
      Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
    } else {      
      wv = (WebView) findViewById(R.id.donate_webView1);
      c = new CustomWebViewClient();
      wv.setWebViewClient(c);
      wv.clearCache(true);
      wv.clearHistory();
      wv.getSettings().setJavaScriptEnabled(true);
      wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
      wv.getSettings().setBuiltInZoomControls(true);
      wv.loadUrl("http://www.google.com");
    }
    
    
    // Function to load all URLs in same webview
    private class CustomWebViewClient extends WebViewClient {
      public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (!DetectConnection.checkInternetConnection(this)) {
          Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
        } else {
          view.loadUrl(url);
        }     
        return true;
      }
    }
    

    Update the Manifest:

    
    

提交回复
热议问题