Friday, August 24, 2012

Check internet connection in android:


Introduction:

  • If you want to check internet connection in device than follow below steps.

Steps:

  • You have to simply put isNetworkAvailable() function in to your class file.
/**
* Checking whether net connection is available or not.
* @param nContext
* @return true if net connection is avaible otherwise false
*/
public static boolean isNetworkAvailable(Context nContext) {
boolean isNetAvailable = false;
if (nContext != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) nContext
.getSystemService(Context.CONNECTIVITY_SERVICE);

if (mConnectivityManager != null) {
boolean mobileNetwork = false;
boolean wifiNetwork = false;

boolean mobileNetworkConnecetd = false;
boolean wifiNetworkConnecetd = false;

NetworkInfo mobileInfo = mConnectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo wifiInfo = mConnectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (mobileInfo != null)
mobileNetwork = mobileInfo.isAvailable();

if (wifiInfo != null)
wifiNetwork = wifiInfo.isAvailable();

if (wifiNetwork == true || mobileNetwork == true) {
mobileNetworkConnecetd = mobileInfo
.isConnectedOrConnecting();
wifiNetworkConnecetd = wifiInfo.isConnectedOrConnecting();
}

isNetAvailable = (mobileNetworkConnecetd || wifiNetworkConnecetd);
}
}
return isNetAvailable;
}

  • Please provide internet permission in your AndroidManifest file.

<uses-permission android:name="android.permission.INTERNET"/>

For Open Internet Setting Screen:

  • Now if there is no internet connection available and you want to navigate on intenet setting screen of your device than use below code.
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivityForResult(intent, 11);



1 comment :

  1. Very Nice blog keep it up brother.. thank you for this common method.

    ReplyDelete