Skip to content

Instantly share code, notes, and snippets.

@guftall
Last active December 11, 2017 18:38
Show Gist options
  • Save guftall/0192e0cac531184ee9ff2727fe496778 to your computer and use it in GitHub Desktop.
Save guftall/0192e0cac531184ee9ff2727fe496778 to your computer and use it in GitHub Desktop.
Android - network working
// this code obtained from telegram android source /DrKLO/Telegram/blob/master/TMessagesProj/src/main/java/org/telegram/tgnet/ConnectionsManager.java
public static boolean isConnectedOrConnectingToWiFi() {
try {
ConnectivityManager connectivityManager = (ConnectivityManager) ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo.State state = netInfo.getState();
if (netInfo != null && (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING || state == NetworkInfo.State.SUSPENDED)) {
return true;
}
} catch (Exception e) {
FileLog.e(e);
}
return false;
}
public static boolean isConnectedToWiFi() {
try {
ConnectivityManager connectivityManager = (ConnectivityManager) ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (netInfo != null && netInfo.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
} catch (Exception e) {
FileLog.e(e);
}
return false;
}
// this code obtained from telegram android source /DrKLO/Telegram/blob/master/TMessagesProj/src/main/java/org/telegram/tgnet/ConnectionsManager.java
public static boolean isNetworkOnline() {
try {
ConnectivityManager connectivityManager = (ConnectivityManager) ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
if (netInfo != null && (netInfo.isConnectedOrConnecting() || netInfo.isAvailable())) {
return true;
}
netInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
netInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
}
} catch (Exception e) {
FileLog.e(e);
return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment