Skip to content

Instantly share code, notes, and snippets.

@nathan-fiscaletti
Last active May 25, 2019 16:39
Show Gist options
  • Save nathan-fiscaletti/ee3e6a1825706b4196a992411e626bd4 to your computer and use it in GitHub Desktop.
Save nathan-fiscaletti/ee3e6a1825706b4196a992411e626bd4 to your computer and use it in GitHub Desktop.
An Android class for retrieving network reachability
package my.app;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class Reachability
{
/**
* Connection Type Definitions.
*/
public enum Connection {
Wifi,
Cellular,
Unknown,
None
}
/**
* The Context we use to access
* the Connectivity Service.
*/
private Context context;
/**
* Initialize the Reachability Object using
* a Context.
*
* @param context The context used to access
* the Connectivity Service.
*/
public Reachability(Context context)
{
this.context = context;
}
/**
* Check if the network is currently Reachable.
*
* @return boolean
*/
public boolean networkReachable()
{
return this.getConnection() != Connection.None;
}
/**
* Retrieve the current Connection type.
*
* @return Reachability.Connection
*/
public Connection getConnection()
{
Connection connection = Connection.None;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) {
return Connection.None;
}
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if ("WIFI".equalsIgnoreCase(ni.getTypeName())) {
if (ni.isConnected())
connection = Connection.Wifi;
} else if ("MOBILE".equalsIgnoreCase(ni.getTypeName())) {
if (ni.isConnected())
connection = (
connection == Connection.None ||
connection == Connection.Unknown
)
? Connection.Cellular
: connection;
} else if (ni.isConnected()) {
connection = (connection == Connection.None)
? Connection.Unknown
: connection;
}
}
return connection;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment