Skip to content

Instantly share code, notes, and snippets.

@lopspower
Last active August 10, 2020 07:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save lopspower/3e93e09f59d15d238908 to your computer and use it in GitHub Desktop.
Save lopspower/3e93e09f59d15d238908 to your computer and use it in GitHub Desktop.
Utility class for the connection management
import android.Manifest;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.annotation.RequiresPermission;
/**
* Copyright (C) 2016 Mikhael LOPEZ
* Licensed under the Apache License Version 2.0
* Utility class for the connection management
*/
public class ConnectionUtils {
//region Singleton ConnectivityManager
private static ConnectivityManager mConnectivityManager;
private static ConnectivityManager getConnectivityManager(Context context) {
if (mConnectivityManager == null)
mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return mConnectivityManager;
}
//endregion
/**
* Shows whether you are connected.
* @param context
* @return true if it is connected to a network, false otherwise
*/
@RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
public static boolean isConnected(Context context) {
NetworkInfo networkInfo = getConnectivityManager(context).getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected());
}
/**
* Return a name describe the type of the network
* @param context
* @return name of the network type "WIFI" or "MOBILE" if is connected, null otherwise
*/
@RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
public static String getConnectionType(Context context) {
return isConnected(context) ? getConnectivityManager(context).getActiveNetworkInfo().getTypeName() : null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment