• Have Any Question?
  • contact@eitworld.com

Checking for Connection





One basic need in the apps that use internet connection is to check if the internet connection is available or not. You can make a way ahead if the connection is available otherwise you may stop the activity.

Step 1- Make an object of class ‘ConnectivityManager’. It is a class of package ‘android.net’. The primary use of this class is to monitor network connections.

ConnectivityManager cm=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

Step 2- Obtain the information about the network in a variable of class NetworkInfo. It is also a class of package ‘android.net’.

NetworkInfo info = (NetworkInfo) cm.getActiveNetworkInfo();

Step 3- If internet connection has been turned on from system settings, info will be equal to ‘null’. If internet connection is turned on, use the method ‘isConnected()’ which returns true when internet is connected and false when connection is not available.

You can use conditional statements to perform your tasks according to the available connectioin.

if (info == null)

{

Log.d(TAG,”No Internet Connection”);

}

else

{

if(info.isConnected())

{

Log.d(TAG,”Internet Connection Available”);

}

else

{

Log.d(TAG,”Connection Not Available”);

}

Step 4- Give following permission in Android.Manifest.xml file-

<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />


Real Time Web Analytics