If else when Internet is Connected | Android studio

When internet is connect on your android app then execute another function, otherwise show message “internet in not connect”. So see code with example.

How to Do

  • Use given code on your project for checking internet connection.
if (isConnected()) {
makeText(MainActivity.this, "Internet is connected", LENGTH_SHORT).show();
} else {
makeText(MainActivity.this, "Check Internet Connection", LENGTH_SHORT).show();
}
  • Defined function’s code for checking internet .
public boolean isConnected() {
    boolean connected = false;
    try {
        ConnectivityManager cm = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo nInfo = cm.getActiveNetworkInfo();
        connected = nInfo != null && nInfo.isAvailable() && nInfo.isConnected();
        return connected;
    } catch (Exception e) {
        Log.e("Connectivity Exception", e.getMessage());
    }
    return connected;
}

See full code with example

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       if (isConnected()) {
makeText(MainActivity.this, "Internet is connected", LENGTH_SHORT).show();
} else {
makeText(MainActivity.this, "Check Internet Connection", LENGTH_SHORT).show();
}
}

    public boolean isConnected() {
        boolean connected = false;
        try {
            ConnectivityManager cm = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo nInfo = cm.getActiveNetworkInfo();
            connected = nInfo != null && nInfo.isAvailable() && nInfo.isConnected();
            return connected;
        } catch (Exception e) {
            Log.e("Connectivity Exception", e.getMessage());
        }
        return connected;
    }
}

Use this code on your project and show internet connection activity. thanks for visiting.