0

I want to check if the device has internet connection. I have found a lot of solutions but I can't do something like this in example:

if(device has Internet connection){
    webview.loadUrl("http://the.url.com")
}
else{
    Toast.makeText(context, text, duration).show()
}
Enve
  • 5,610
  • 10
  • 35
  • 78

2 Answers2

7

Put this method in the class you want to check connectivity:

public static boolean isOnline(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnected()) {
       return true;
    }
    return false;
}

Then when you need to check connection, do this (using your example):

if(isOnline(getApplicationContext()){
    webview.loadUrl("http://the.url.com")
}
else{
    Toast.makeText(context, text, duration).show()
}

You can also create that method in a class and always use it from there, like ExampleClass.isOnline().

Do not forget to add this to your AndroidManifest:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Rodrigo Venancio
  • 1,234
  • 1
  • 12
  • 17
2

This is a small example:

try {
    URL url = new URL("http://the.url.com");
    URLConnection conn = url.openConnection();
    conn.connect();
    webview.loadUrl("http://the.url.com");
} catch (MalformedURLException e) {
    // the URL is not in a valid form
    Toast.makeText(context, text, duration).show();
} catch (IOException e) {
    // the connection couldn't be established
    Toast.makeText(context, text, duration).show()
}
ᗩИᎠЯƎᗩ
  • 2,076
  • 5
  • 26
  • 39