I have the code below, which is intended to check if the network being used is Cell or WiFi. If WiFi then return the string WiFi and if cell return the string Cell. The code I have is:
private String checkNetworkState() {
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
// NetworkInfo mEthernet = connManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
NetworkInfo m3G = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mWifi!=null) isOnWifi = mWifi.isConnected();
if (m3G!=null) is3G = m3G.isConnected();
if(isOnWifi == true) {
return "WiFi";
}
else {
return "Cell";
}
}
I have debugged with WiFi enabled. isOnWifi is true and is3G is false. However, both the if AND the else get called, why is this happening?
Having said that the return string I get is actually "WiFi", not Cell. Is this usual?
if you are checking network state you have to change your method,
private boolean checkNetworkState() {
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo m3G = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mWifi!=null) isOnWifi = mWifi.isConnected();
if (m3G!=null) is3G = m3G.isConnected();
if(isOnWifi == true || is3G == true) {
return true;
}
return false;
}
you can´t get two values from the same method, try using the respective method for each case:
public boolean isConnectedWifi() {
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
return mWifi.isConnected();
}
public boolean isConnectedMobile() {
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo m3G = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
return m3G.isConnected();
}