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

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

    You can check device is connect to internet through data or wifi by following code

    ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo i = manager.getActiveNetworkInfo();
    boolean hasConnect = (i!= null && i.isConnected() && i.isAvailable());
    
    if(hasConnect)
                        {
                           // show the webview
                        }
    else
     {
        // do what ever you need when when no internet connection
     }
    

    After user go to webview , then if the connect is lost you can capture that event from following code

     webView.setWebViewClient(new Callback());
    
     public class Callback extends WebViewClient{
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
            Toast.makeText(getApplicationContext(), "Failed loading app!, No Internet Connection found.", Toast.LENGTH_SHORT).show();
    
    
        }
    }  
    

    following permissions need to give

提交回复
热议问题