Skip to content

Instantly share code, notes, and snippets.

@Jeevuz
Created September 19, 2016 11:34
Show Gist options
  • Save Jeevuz/a747e838a8922cf46467cc5f6eae13f8 to your computer and use it in GitHub Desktop.
Save Jeevuz/a747e838a8922cf46467cc5f6eae13f8 to your computer and use it in GitHub Desktop.
package ru.mobileup.grushasdk.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
/**
* @author Vasili Chyrvon ([email protected])
*/
public class ConnectionUtils {
private ConnectionUtils() {
//no instance
}
public static boolean hasConnection(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
public static boolean is3gAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
Network[] networks = connectivityManager.getAllNetworks();
for (Network network : networks) {
NetworkInfo ni = connectivityManager.getNetworkInfo(network);
if (ni.getType() == ConnectivityManager.TYPE_MOBILE) {
networkInfo = ni;
break;
}
}
} else {
//noinspection deprecation
networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
}
boolean is3gAvailable = networkInfo != null && networkInfo.isAvailable();
Loggi.d(String.format("3G is %s.", is3gAvailable ? "available" : "NOT available"));
return is3gAvailable;
}
/**
* Changes WiFi state
* @param newState new state. true - enable, false - disable
* @return true - state changed, false - state not changed, because WiFi already in needed state
*/
public static boolean changeWiFiEnabled(Context context, boolean newState) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
boolean currentState = wifiManager.isWifiEnabled();
if (currentState != newState) {
wifiManager.setWifiEnabled(newState);
Loggi.d(String.format("WiFi turned %s.", newState ? "ON" : "OFF"));
return true;
} else {
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment