You can see other best Android Gists or offer your just here https://github.com/lopspower/BestAndroidGists 👍.
-
-
Save lopspower/3e93e09f59d15d238908 to your computer and use it in GitHub Desktop.
Utility class for the connection management
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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