Tag Archives: network

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

Registering for Broadcast through AndroidManifest

Here is a small tip that took me a while to figure out but hopefully will save someone time and frustration. I have a BroadcastReceiver in my application that listens for network connectivity changes so the app. can resume background work on network availability.

If you register for receiver in AndroidManifest.xml then you need to write the actual constant value inside the <intent-filter> tag:

       <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>

The value is for the intent constant ConnectivityManager.CONNECTIVITY_ACTION. There are no warning or exceptions if you put this constant variable straight away in AndroidManifest.xml but the receiver won’t catch the network change events so a little hard to debug.

Note that if you register for a broadcast receiver from within code then just referring to the constant will work fine.