Tag Archives: internet

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"/>