简体   繁体   中英

Prevent WebView from displaying “No Internet!”

I have a web view in my app in android studio. I have a web view in my app and I want to make a popup saying "no internet" if there is no internet and a "ok" button on the popup which will recheck if there is no internet and if there is internet it will let the web page load and if not it says "no internet". I am a beginner programmer so please keep the code simple

My Code: (mainactivity)

package com.myworldrules.test.testno;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

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.myWebView);
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.loadUrl("http://space.myworldrules.com/");


        myWebView.setWebViewClient(new WebViewClient());



    }

}

Please feel free to ask any questions

This can be accomplished by accessing the ConnectivityManager and requesting the active network info. That alone may not always be sufficient so you can additionally determine if a site like google is accessible(in case there is a chance the server you are trying to access is down). Please see the link below;

Android check internet connection

检查是否有活动的网络连接,如果不存在,您可以执行以下操作

            webView.loadData("", null, "");

You can check if there is internet available or not before loading url in to webview and

if available

load url in webview

else

create alert dialog for popup

to check internet connection follow this answer here

只需使用,它应该可以工作:

mWebview.loadDataWithBaseURL(null,htmlContent,"text/html", "utf-8", null);

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