Skip to content Skip to sidebar Skip to footer

How To Check The Network Availability?

I have to connect my app with server using either wifi (if it is available), or gprs (if wifi is not available). Here is my code to check the connection availability public static

Solution 1:

The following very similar approach works, but has the added advantage of not caring what the underlying medium, since it looks as though there is support for more than just WiFi. Maybe these are also covered by mobile, but the docs aren't super clear:

// added as an instance method to an ActivitybooleanisNetworkConnectionAvailable() {  
    ConnectivityManagercm= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfoinfo= cm.getActiveNetworkInfo();     
    if (info == null) returnfalse;
    Statenetwork= info.getState();
    return (network == NetworkInfo.State.CONNECTED || network == NetworkInfo.State.CONNECTING);
}     

Solution 2:

Network Availability Check :

privatebooleanisNetworkAvailable() {
    ConnectivityManagerconnectivityManager= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfoactiveNetworkInfo= connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

Solution 3:

Or you could use some kotlin implementation

fun Context.isNetworkAvailable(): Boolean {
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
return activeNetwork?.isConnectedOrConnecting == true

}

Post a Comment for "How To Check The Network Availability?"