开发者

Android getWifiState to String

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
开发者_StackOverflow

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.


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.


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";
    }
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜