Checking Type of Internet Connection Wifi/Mobile

There are primarily two ways of connecting to internet in android. It can be either wifi or 3G (mobile data connection). If its a wifi connection and the application wants the wifi connection to stay active while the device goes to sleep then acquire a wifi lock and release it when the application is finished with internet related work otherwise the application will lose connectivity after devices goes to sleep. On the other hand 3G does not requires any type of lock to stay awake. A code can inquire about the type of network a device is connected to using following piece of code:

ConnectivityManager conManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiInfo = conManager.getNetworkInfo((ConnectivityManager.TYPE_WIFI));
NetworkInfo mobileInfo = conManager.getNetworkInfo((ConnectivityManager.TYPE_MOBILE));

if (wifiInfo.isConnectedOrConnecting() )
       Log.v("NetworkState", "Connected or connecting to wifi");
else if (mobileInfo.isConnectedOrConnecting())
       Log.v("NetworkState", "Connected or connecting to mobile data connection");

Add the following permission to the application AndroidManifest.xml otherwise the application will throw a run time exception:

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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s