-5

How can I get connection is available or not on Android?

I tried lots of code, but I did not get the correct result.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kavita
  • 7
  • 5

2 Answers2

3

Put in this function and call it at the starting of your Activity:

void checkInternetConnectionStatus()
{
    ConnectivityManager connMgr = (ConnectivityManager) this
        .getSystemService(Context.CONNECTIVITY_SERVICE);

    android.net.NetworkInfo wifi = connMgr
        .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    android.net.NetworkInfo mobile = connMgr
        .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    if (wifi.isAvailable()) {
        /*
         * Toast.makeText(this, "Wi-Fi connection enabled",
         * Toast.LENGTH_LONG) .show();
         */
    } else if (mobile.isAvailable()) {
        /*
         * Toast.makeText(this, "Mobile Internet enabled",
         * Toast.LENGTH_LONG) .show();
         */

    } else {
        Toast.makeText(this, "No Internet Connection", Toast.LENGTH_LONG)
            .show();

        new AlertDialog.Builder(this)
            .setTitle("No internet connection active")
            .setMessage("Please start internet connection and run this application.")
            .setNegativeButton(
                "Exit",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Log.d("AlertDialog", "Negative");
                        finish();
                    }
                }).show();
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dhaval Patel
  • 694
  • 4
  • 12
1

Maybe this will help:

 ConnectivityManager conn = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo wifi = conn.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (wifi.isConnected()) {
    // Do your code
}

And also you need to add in AndroidManifest.xml:

android.permission.ACCESS_NETWORK_STATE

And also this link will help:

NetworkInfo

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hariharan
  • 24,741
  • 6
  • 50
  • 54