Wednesday, August 12, 2015

How to Determine the Connectivity Status In Android

While developing the Android applications, most common use cases is to schedule regular updates of application data from Internet resources, cache data, or execute long running downloads. 
But if you aren't connected to the Internet, or the connection is too slow to complete your download, why the waking the device to schedule the update at all?  So before you trigger any of these activity we need to check the connectivity status.

You can use the ConnectivityManager to check that you're actually connected to the Internet, and if so, what type of connection is in place. Is it wifi, gprs etc?

The following snippet shows how to use the ConnectivityManager to query the active network and determine if it has Internet connectivity:

ConnectivityManager cm =
 NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
It's also possible to determine the type of Internet connection currently available.
Device connectivity can be provided by mobile data, WiMAX, Wi-Fi, and ethernet connections. By querying the type of the active network, as shown below, you can alter your refresh rate based on the bandwidth available.
boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
if  "iswifi" is true then the device is using wifi connrction, That's it. Happy coding.

No comments: