简体   繁体   中英

Prevent WebView from Loading if no internet

I programmed an app which opens a WebView via Imagebutton. If there is no Internet and the app is started a little popup comes up which says "No Internet". If i started the app with Internet and i lost the Internet during using the WebView a very ugly Screen shows up with error. How can i prevent my Webview loading a new side if there is no Internet, a small Toast should open or Textfield with "Sorry you lost your Connection :/", thanks!

Here my Code

public static boolean checkInternetConnection(Context context) {
        ConnectivityManager con_manager = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (con_manager.getActiveNetworkInfo() != null
                && con_manager.getActiveNetworkInfo().isAvailable()
                && con_manager.getActiveNetworkInfo().isConnected()) {
            return true;
        } else {
            return false;
        }
    }
    private ImageButton Ilias_link;
    private ImageButton Lsf_link;
    private WebView mWebView;
    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AdView mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
        if (!MainActivity.checkInternetConnection(this)) {
            Toast.makeText(getApplicationContext(), "Du hast leider kein Internet", Toast.LENGTH_SHORT).show();
        } else {
            Ilias_link = (ImageButton) findViewById(R.id.ilias_link);
        mWebView = new WebView(this);
        Ilias_link.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mWebView.getSettings().setJavaScriptEnabled(true);
                mWebView.getSettings().setBuiltInZoomControls(true);
                mWebView.getSettings().setDisplayZoomControls(false);
                mWebView.getSettings().setSupportZoom(true);
                if (savedInstanceState == null)
                    mWebView.loadUrl("https://elearns02.fh-biberach.de/ilias3/login.php?target=&soap_pw=&ext_uid=&cookies=nocookies&client_id=HSBC&lang=de");
                    mWebView.setWebViewClient(new WebViewClient());
                    setContentView(mWebView);}
        });
            Lsf_link = (ImageButton) findViewById(R.id.lsf_link);
            mWebView = new WebView(this);
            Lsf_link.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    mWebView.getSettings().setJavaScriptEnabled(true);
                    mWebView.getSettings().setBuiltInZoomControls(true);
                    mWebView.getSettings().setDisplayZoomControls(false);
                    mWebView.getSettings().setSupportZoom(true);
                    if (savedInstanceState == null)
                        mWebView.loadUrl("https://lsf.fh-biberach.de/qisserver/rds?state=user&type=0");
                    mWebView.setWebViewClient(new WebViewClient());
                    setContentView(mWebView);{
                    }};


            })
            ;}
    ImageButton imageButton = (ImageButton)findViewById((R.id.Mensaplan));
    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this, "Comming soon ;)",Toast.LENGTH_LONG).show();
        }
    });}
    public void onPageFinished(WebView view, String url) {
        String javascript="javascript:document.getElementsByName('viewport')[0].setAttribute('content', 'initial-scale=1.0,maximum-scale=10.0');";
        view.loadUrl(javascript);
    }
    @Override
    protected void onSaveInstanceState(Bundle outState )
    {
        super.onSaveInstanceState(outState);
        mWebView.saveState(outState);
    }
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);
        mWebView.restoreState(savedInstanceState);
    }
    private static final int TIME_INTERVAL = 3000;
    private long mBackPressed;
    @Override
        public void onBackPressed() {
            if (mWebView.canGoBack()) {
                mWebView.goBack();
                return;
            } else
            { if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis())
            {
                super.onBackPressed();
                return;
            }
            else { Toast.makeText(getBaseContext(), "Tap back button in order to exit", Toast.LENGTH_SHORT).show(); }
                mBackPressed = System.currentTimeMillis();

            }
    }
}

Try doing this - May be it will work. I made a project and used this.

DetectConnection.java

public class DetectConnection {             
public static boolean checkInternetConnection(Context context) {   

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

if (con_manager.getActiveNetworkInfo() != null
    && con_manager.getActiveNetworkInfo().isAvailable()
    && con_manager.getActiveNetworkInfo().isConnected()) {
  return true;
} else {
  return false;
}
}
}

The main code will be :-

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;
}
}

I hope it works :)

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