-2

I'd like to create a button to go to another activity for webview. Before going to the next activity I like to check internet connection: if device is connected, OK, go to the next activity. if not, Toast a message like this "No Internet Connection". However, I don't want the device go to the respected activity. I've tried different method explained in this website but didn't work. Tnx a bunch guys.

  • Paste the code you've tried so far. – jlively Nov 17 '18 at 11:33
  • You can do it in different manners. I can suggest to read [this](https://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-times-out). – Calaf Nov 17 '18 at 11:35
  • 1
    Possible duplicate of [Check internet connection on button click](https://stackoverflow.com/questions/35647067/check-internet-connection-on-button-click) – Sagar Zala Nov 17 '18 at 11:55

2 Answers2

1

Add the permission to the Manifest - <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Then, use this method to check whether the user has connection

/**
 * Check if it has an active connection.
 *
 * @param context some Context.
 * @return does it have an active Network connection.
 */
public static boolean hasActiveNetworkConnection(Context context) {
    ConnectivityManager connMgr = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    return ((networkInfo != null) && networkInfo.isConnected());
}

This will give you the state. Based on that, fire the Intent for the other activity.

jlively
  • 735
  • 2
  • 9
  • 29
1
     if (isOnline(DashBoardActivity.this))  // checks if internet is on or off
         Toast.makeText(DashboardActivity.this, "Please connect to internet and try again", Toast.LENGTH_SHORT).show();
     else {
startActivity(intent)
}  

 public boolean isOnline(Activity activity) {
    ConnectivityManager cm = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    } else {
        return false;
    }
}
Kevin Kurien
  • 812
  • 6
  • 14