0

Someone please help me, I've been trying to solve this for 10 hours, I'm using android studio to make an app with WebView of my website, and I want to add a customized page for the case of no internet.

But, internet detection is always positive, even when I turn off the Wifi from the notebook. Always open the page of the "if" (I've tried to invert the pages) never the "else" page.

What's wrong with the code? Is there an easier way to place the page for when there is no internet?

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Base64;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends Activity {

    private WebView webView = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PreferenceManager.setDefaultValues(this, R.xml.config, false);
        setContentView(R.layout.activity_main);
        this.webView = (WebView) findViewById(R.id.webview);

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setAppCacheEnabled(false);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        WebViewClientImpl webViewClient = new WebViewClientImpl(this);
        webView.setWebViewClient(webViewClient);

        webView.clearCache(true);
        webView.clearHistory();
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

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

        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            webView.loadUrl("www.google.com");
        } else{
        webView.loadUrl("file:///android_asset/seminternet.html");}

'''

John
  • 21
  • 3
  • `I turn off the Wifi from the notebook. ` ? Notebook? Does your Android app run on a notebook? – blackapps Jul 02 '20 at 09:05
  • There is nothing in your code that checks an internet connection. – blackapps Jul 02 '20 at 09:08
  • Yes, I have the android studio emulator. – John Jul 02 '20 at 09:10
  • The last four lines theoretically checks the connection, I got this here on overflow – John Jul 02 '20 at 09:11
  • Your app runs on an emulator. You should switch of the wifi of the emulator of course. But maybe that is not possible. Please try. – blackapps Jul 02 '20 at 09:12
  • `The last four lines theoretically checks the connection, `. No. Only if there is a wifi connection. With a router for instance. Not if internet is availble. You better take a real device to test such things. – blackapps Jul 02 '20 at 09:14
  • Oh my god, if I disable the emulator wifi the code works perfectly '-' – John Jul 02 '20 at 09:17
  • Just try to load google.com and if it fails show a page from assets. That is THE way to check internet connection. – blackapps Jul 02 '20 at 09:17
  • `if I disable the emulator wifi the code works perfectly ` It does not say that much. For instance switch off your router or the wifi of your laptop. You have no internet then. But your code will still tell you that you have. You have seen that before. Nothing learned. – blackapps Jul 02 '20 at 09:20

1 Answers1

0

The method you are using is deprecated.

Method 1: Java Helper Function:

@IntRange(from = 0, to = 3)
public static int getConnectionType(Context context) {
    int result = 0; // Returns connection type. 0: none; 1: mobile data; 2: wifi
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (cm != null) {
            NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
            if (capabilities != null) {
                if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                    result = 2;
                } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                    result = 1;
                } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) {
                    result = 3;
                }
            }
        }
    } else {
        if (cm != null) {
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            if (activeNetwork != null) {
                // connected to the internet
                if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                    result = 2;
                } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                    result = 1;
                } else if (activeNetwork.getType() == ConnectivityManager.TYPE_VPN) {
                    result = 3;
                }
            }
        }
    }
    return result;
}

Usage:

int type = getConnectionType(getApplicationContext());

Method 2:(Source: Developer.android.com)

ConnectivityManager cm =(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

Note: getActiveNetworkInfo() was deprecated in Android 10.

Method 3:

public boolean isInternetAvailable() {
    try {
        InetAddress ipAddr = InetAddress.getByName("google.com"); 
            return !ipAddr.equals("");

        } catch (Exception e) {
            return false;
    }
}
fatalcoder524
  • 1,428
  • 1
  • 7
  • 16
  • This is wrong, you're not checking if the active network is connected pre-M, nor are you checking what capabilities (such as internet access) in the M+ branch. – Ryan M Jul 02 '20 at 09:38
  • my god, it's impossible to find a so simple code. I've tried everything – John Jul 02 '20 at 09:39
  • @RyanM What about now? – fatalcoder524 Jul 02 '20 at 09:41
  • It's still not checking if the connection is _connected_. You want to check https://developer.android.com/reference/android/net/NetworkCapabilities#NET_CAPABILITY_INTERNET and https://stackoverflow.com/a/4009133/208273 – Ryan M Jul 02 '20 at 09:45
  • @RyanM What about method 3? – fatalcoder524 Jul 02 '20 at 09:55
  • That will work, though keep in mind that's a blocking network call, so you can't do that on the main thread. – Ryan M Jul 02 '20 at 10:08