Check a Device's Network Connection with complete example

Device can have two types of network connections, either a Wi-Fi or a mobile network connection. If a network connection is unavailable, android application should not respond properly.
To check the network connection, you typically use the following classes:
Check a Device's Network Connection
Connectivity Manager
Network Info
ConnectivityManager class:
You need to instantiate an object of getSystemService class by calling getSystemService() method. Its syntax is given below:
ConnectivityManager connectivitymanager = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
ConnectivityManager method returns an array of NetworkInfo. So you have to receive it like this.
NetworkInfo[] info = connectivitymanager .getAllNetworkInfo();
And you need to declear intrernet permission in your manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Your final code is:
public static boolean isNetworkAvailable(Context context) {
final ConnectivityManager connectivitymanager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivitymanager.getActiveNetworkInfo();
if (activeNetworkInfo != null) { // connected to the internet
if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
Toast.makeText(context, "Internet is connected", Toast.LENGTH_SHORT).show();
return true;
} else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to the mobile provider's data plan
Toast.makeText(context, "Internet is connected", Toast.LENGTH_SHORT).show();
return true;
}
}
Toast.makeText(context, "Internet is not connected", Toast.LENGTH_SHORT).show();
return false;
}
Write a comment