简体   繁体   中英

webview not connected to the internet page

How can i make it so that when a user of my app is not connected to the internet they receive a error message asking them to connect to the internet?

My main activity code:

public class MainActivity extends AppCompatActivity {

private WebView mywebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mywebView = (WebView) findViewById(R.id.webView);
    WebSettings webSettings = mywebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    mywebView.loadUrl("http://holidayhomes.ca/");
    mywebView.setWebViewClient(new WebViewClient());
    mywebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
}

@Override
public void onBackPressed() {
    if(mywebView.canGoBack())
        mywebView.goBack();
    super.onBackPressed();

}

}

Use the ConnectivityManager:

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

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
                  activeNetwork.isConnectedOrConnecting();

If isConnected is false, you can display a toast to the user.

Toast.makeText(context, "You must have a network connection", Toast.LENGHT_SHORT);

将Internet权限添加到manifest.xml

<uses-permission android:name="android.permission.INTERNET" />

Override onPageStart method of WebviewClient and check for internet connection and show error msg.

webview.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if (isConnected()) {
                //Internet is connected
            } else{
                //set error msg
            }
        }
}

public boolean isConnected(){
    ConnectivityManager cm =
    (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

     retrun isConnected;

}

Please check your android manifest file whether you have added internet permission or not. Please you didn't provide internet permission web view can't load webpage even you can't call any internet related operation. you can add permission by adding below tag in android manifest file.

<uses-permission android:name="android.permission.INTERNET" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM