views:

108

answers:

2

I am attempting to get the string representation of an Android device's current WiFi state. I am using the getWifiState() method of the WiFiManager and am getting an integer returned depending on the current state. This makes total sense as getWifiState() is supposed to return an integer. The method's documentation indicates that the possible return values translate to one of the following constant values

  • 0 WIFI_STATE_DISABLING
  • 1 WIFI_STATE_DISABLED
  • 2 WIFI_STATE_ENABLING
  • 3 WIFI_STATE_ENABLED
  • 4 WIFI_STATE_UNKNOWN

Is there an easy way to translate the integer returned from getWiFiState() to a string representation? I've looked at getIntExtra but am unsure of its use.

A: 

How about just:

  public String getWifiStateStr() {
    switch (mWifiManager.getWifiState()) {
      case 0:
        return "disabling";
      case 1:
        return "disabled";
      case 2:
        return "enabling";
      case 3:
        return "enabled";
      default:
        return "unknown";
    }
  }
JRL
I thought of that, but was wondering if there was a less brittle way. I doubt the integers translated value is going to change very often but something about a switch in this instance just seems wrong. That said beggars can't be choosers and this may be the best possible mechanism.
ahsteele
Since the only information concerning the "meaning" of those integers are the variable names themselves, the only other option would be to use reflection, which would certainly be *much more brittle* and terribly inefficient.
JRL
@JRL very true.
ahsteele
+1  A: 

i know you already accepted an answer but you should not use the code posted because, as you said, it is brittle and difficult to maintain. There is no reason for it to be so.

  public String getWifiStateStr() {
    switch (mWifiManager.getWifiState()) {
      case WifiManager.WIFI_STATE_DISABLING:
        return "disabling";
      case WifiManager.WIFI_STATE_DISABLED:
        return "disabled";
      case WifiManager.WIFI_STATE_ENABLING:
        return "enabling";
      case WifiManager.WIFI_STATE_ENABLED:
        return "enabled";
      case WifiManager.WIFI_STATE_UNKNOWN:
        return "unknown";
      default:
        return null;  //or whatever you want for an error string
    }
  }

This protects you from changes in the constant assignment, will be much easier to read in 6 months, and assuming you handle the error string correctly should limit bugs if the number of allowed return values increases.

When you see a variable listed as a 'Constant' in Android documentation it means that it is declared public static final. It can be accessed as ClassName.CONST_VARIABLE_NAME. It is convention that these variables will be in all caps but it is not a language requirement. Generally speaking you should never need to use the actual value of such members, you should always access them by member name unless you need to do something odd.

Mark