In the previous tutorial we had a discussion about knowing the Battery Status. In this tutorial I’ll show you how to check the connectivity status. There is a class called ConnectivityManager which is used to check whether our device is connected to the Internet or not, and if connected then of what type. This class is available since API 1. ConnectivityManager is the answer to know all about the network connectivity state. It also notifies whenever the connectivity status change.
The primary responsibilities of this class are to:
1. Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)
2. Send broadcast intents when network connectivity changes
3. Attempt to “fail over” to another network when connectivity to a network is lost
4. Provide an API that allows applications to query the coarse-grained or fine-grained state of the available networks
5. Provide an API that allows applications to request and select networks for their data traffic
Call Context.getSystemService(Context.CONNECTIVITY_SERVICE) to get the instance of ConnectivityManager Class.
HOW TO DETECT NETWORK CONNECTIVITY
1. We will get the instance of ConnectivityManager Class,
2. getActiveNetworkInfo, this will returns details about the currently active default data network
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getNetworkInfoInfo(); boolean isConnected = networkInfo != null && networkInfo.isConnectedOrConnecting();
This isConnected will give you the results.
ConnectivityManager.WIFI : This will determine the type of Internet Connection available.
Register this in manifest. This broadcast will be triggered every time when your devices moves from one connectivity to another.